Hey all,
I have (or so I think!) a simple problem.
I will greatly simplify my model to speed this along.
I have a model class lets call it item:
public class Item
{
[Required(ErrorMessage="Must indicate if product is to be tracked by serial number.")]
public bool TrackedBySerial { get; set; }
}
I have an "Add" view where I create a DropDownList like so:
<%= Html.DropDownListFor(model=>model.TrackedBySerial, new SelectList(new List<object> {null,true,false},null),"Select One") %>
<%= Html.ValidationMessageFor(model => model.TrackedBySerial) %>
My problem is that unless I create my boolean value in the model to be a nullable type, I can't force the blank default value.
If I use the Html.DropDownList() instead of DropDownListFor() , is there any way for me to use ModelState.IsValid -- or do I need to mix my own custom validation in my controller as well?
Update: So I got the functionality I was looking for, its just a bit more verbose than I'd have liked. Is there a better way to do this?
Controller:
[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);
}
view:
<div class="editor-field">
<%=Html.DropDownList("TrackBySerial","- Select One- ") %>
<%=Html.ValidationMessage("TrackBySerial") %>
<%= Html.ValidationMessageFor(model => model.TrackedBySerial) %>
</div>