1
我有(或者我觉得!)一个简单的问题。ASP.NET MVC 2 - DropDownFor - 强制用户为非空类型选择一个值?
我会大大简化我的模型,以加快这一点。
我有一个模型类可以称之为项目:
public class Item
{
[Required(ErrorMessage="Must indicate if product is to be tracked by serial number.")]
public bool TrackedBySerial { get; set; }
}
我有一个“添加”的观点,我创建像这样一个DropDownList:
<%= Html.DropDownListFor(model=>model.TrackedBySerial, new SelectList(new List<object> {null,true,false},null),"Select One") %>
<%= Html.ValidationMessageFor(model => model.TrackedBySerial) %>
我的问题是,除非我创建我的模型中的布尔值是一个可为空的类型,我不能强制空白默认值。
如果我使用Html.DropDownList()而不是DropDownListFor(),是否有任何方法可以让我使用ModelState.IsValid - 或者是否需要在我的控制器中混合自己的自定义验证?
更新:所以我得到了我正在寻找的功能,它只是比我想要的更冗长。有一个更好的方法吗?
控制器:
[HttpPost]
public ActionResult Add(InventoryItem newItem)
{
try
{
//get the selected form value
string formVal = Request.Form["TrackBySerial"];
//convert to true, false, or null
bool? selectedValue = TryParseNullable.TryParseNullableBool(formVal);
//if there is no value, add an error
if (!selectedValue.HasValue)
{
ModelState.AddModelError("TrackBySerial", "You must indicate whether or not this part will be tracked by serial number.");
}
else
{//otherwise add it to the model
newItem.TrackedBySerial = selectedValue.Value;
}
if (ModelState.IsValid)
{
//add part into inventory
newItem.ID = inventory.AddNewProduct(newItem).ToString();
//log the action
logger.LogAction(ActionTypes.ProductCatalog, Request.LogonUserIdentity.Name, "Added new product: " + newItem.PartNumber);
//put into QA queue here?
//redirect to edit screen to add suppliers
return RedirectToAction("Edit", new { id = newItem.ID });
}
ViewData["TrackBySerial"] = new SelectList(new object[] { true, false },selectedValue);
return View(newItem);
}}
/// <summary>
/// Form for adding new catalog entries
/// </summary>
/// <returns></returns>
/// GET: /Purchasing/Catalog/Add
public ActionResult Add()
{
InventoryItem newItem = new InventoryItem();
ViewData["TrackBySerial"] = new SelectList(new object[] { true, false });
return View(newItem);
}
观点:
<div class="editor-field">
<%=Html.DropDownList("TrackBySerial","- Select One- ") %>
<%=Html.ValidationMessage("TrackBySerial") %>
<%= Html.ValidationMessageFor(model => model.TrackedBySerial) %>
</div>