ModelState.IsValid
始终为 false,因为我在要提交的表单中使用了下拉列表,但出现此异常:
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<SelectListItem> BloodGroup { get; set; }
}
查看:
<div class="form-group">
@Html.LabelFor(m => m.BloodGroup, new { @class = "control-label col-md-3" })
<div class="col-md-4">
@Html.DropDownListFor(m => m.BloodGroup, Model.BloodGroup, "Please Select", new { @class = "form-control" })
</div>
</div>
Controller :
[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<SelectListItem> BloodGroups { get; set; }
}
<div class="form-group">
@Html.LabelFor(m => m.BloodGroup, new { @class = "control-label col-md-3" })
<div class="col-md-4">
@Html.DropDownListFor(m => m.BloodGroup, Model.BloodGroups, "Please Select", new { @class = "form-control" })
</div>
</div>
您并没有发布下拉列表中的所有项目,您只是发布了所选项目的值。在我的示例中,我假设它是一个 int(可能是主键值)。
如果 POST 验证失败,您需要再次重新填充这些值:
if (!ModelState.IsValid)
{
model.BloodGroups = GetBloodGroups();
ModelState.AddModelError("Employee", "Model is Not Valid");
return View("Employee", model);
}
关于c# - 使用下拉列表时的 Asp.net mvc ModelState 有效性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21992167/