繁体   English   中英

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

[英]Asp.net mvc ModelState validity when using dropdownlist

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>

控制器:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM