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

时间:2014-02-24 15:39:15

标签: c# asp.net asp.net-mvc asp.net-mvc-4 model

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

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>

控制器:

 [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;
        }
    }

1 个答案:

答案 0 :(得分:6)

这不是您使用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);
}