我有这个 ViewModel:
public class CreateUserModel {
public int StateId { get; set; }
public IEnumerable<SelectListItem> States { get; set; }
}
这是我的观点:
@Html.DropDownListFor(model => model.StateId, Model.States, "--select state--")
这是我的控制器:
public ActionResult Create()
{
var model= new CreateUserModel();
model.States = new SelectList(_context.States.ToList(), "Id", "Name");
return View(model);
}
[HttpPost]
public ActionResult Create(CreateUserModel model)
{
if (ModelState.IsValid)
{
_context.Users.Add(new User()
{
StateId = model.StateId
});
_context.SaveChanges();
return RedirectToAction("Index");
}
else
{
return View(model);
}
}
此错误使 ModelState 无效:
System.InvalidOperationException:从类型“System.String”到类型“System.Web.Mvc.SelectListItem”的参数转换失败,因为没有类型转换器可以在这些类型之间进行转换。
编辑以包括我的完整视图:
@model AgreementsAndAwardsDB.ViewModels.CreateUserModel
<!DOCTYPE html>
<html>
<head>
<script src="~/Scripts/jquery-1.8.3.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
</head>
<body class="createPage">
@using (Html.BeginForm("Create", "Accounts", Model, FormMethod.Post))
{
@Html.DropDownList("StateId", Model.States)
<input type="submit" />
}
</body>
</html>