我的 MVC 应用程序出现错误。我有一些文本字段和一个下拉列表的页面。当我提交页面时,数据正确加载到该页面,ModelState 返回错误
The parameter conversion from type 'System.String' to type 'System.Web.Mvc.SelectListItem' failed because no type converter can convert between these types.
Controller 方法
public ActionResult Edit(string id)
{
....
EditUserViewModel vm = new EditUserViewModel()
.... // populate the view model including its SelectList properties
return View(vm);
}
数据已按照下图正确填充
但是当它提交回 Controller 时,模型状态无效并给出错误。
和 View 模型
public class EditUserViewModel
{
public string UserID { get; set; }
public string SelectedRoleName { get; set; }
public IEnumerable<SelectListItem> Roles { get; set; }
public string SelectedCompanyID { get; set; }
public IEnumerable<SelectListItem> Companies { get; set; }
....
}
View 如下
....
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.HiddenFor(model => model.UserID)
@Html.DropDownListFor(model => model.SelectedRoleName, Model.Roles)
@Html.DropDownListFor(model => model.SelectedCompanyID, Model.Companies,
@Html.HiddenFor(model => model.Companies)
....
<input type="submit" value="Save" class="btn btn-default" />
}
请您参考如下方法:
错误是因为 View 中有如下一行代码
@Html.HiddenFor(model => model.Companies)
如果您检查它生成的 html,它将是
<input ... name="Companies" value="System.Collections.Generic.List`1[System.Web.Mvc.SelectListItem]" />`
当您提交表单时,DefaultModelBinder尝试绑定(bind)属性 Companies到该值并失败(您不能将 IEnumerable<SelectListItem> 的属性绑定(bind)到 string )。
删除那行代码。如果您需要返回 View ,因为 ModelState由于其他原因无效,然后在返回 View 之前重新填充 SelectLists。
