使用dropdownlist时Asp.net mvc ModelState的有效性

ModelState.IsValid总是false,因为我在我想提交的表单中使用了一个下拉列表,我得到了这个exception:

 The parameter conversion from type 'System.String' to type 'System.Web.Mvc.SelectListItem' failed because no type converter can convert between these types 

模型:

 public class NewEmployeeModel { [Required(ErrorMessage = "*")] [Display(Name = "Blood Group")] public IEnumerable BloodGroup { get; set; } } 

视图:

 
@Html.LabelFor(m => m.BloodGroup, new { @class = "control-label col-md-3" })
@Html.DropDownListFor(m => m.BloodGroup, Model.BloodGroup, "Please Select", new { @class = "form-control" })

控制器:

  [HttpPost] public ActionResult Employee(NewEmployeeModel model) { var errors = ModelState .Where(x => x.Value.Errors.Count > 0) .Select(x => new { x.Key, x.Value.Errors }) .ToArray(); if (!ModelState.IsValid) { ModelState.AddModelError("Employee", "Model is Not Valid"); return View("Employee", model); } else { return null; } } 

这不是您使用SelectList的方式

您需要另一个模型属性来保存BloodGroup的选定值:

 public class NewEmployeeModel { [Required(ErrorMessage = "*")] [Display(Name = "Blood Group")] public int BloodGroup { get; set; } public IEnumerable BloodGroups { get; set; } } 
@Html.LabelFor(m => m.BloodGroup, new { @class = "control-label col-md-3" })
@Html.DropDownListFor(m => m.BloodGroup, Model.BloodGroups, "Please Select", new { @class = "form-control" })

您没有在下拉列表中发布所有项目,只发布所选项目的值。 在我的例子中,我假设它是一个int(也许是主键值)。

如果POST上的validation失败,则需要再次重新填充这些值:

 if (!ModelState.IsValid) { model.BloodGroups = GetBloodGroups(); ModelState.AddModelError("Employee", "Model is Not Valid"); return View("Employee", model); }