1

我有这个 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>
4

1 回答 1

3

您正在使用以下行将模型作为路由值传递给表单操作:

@using (Html.BeginForm("Create", "Accounts", Model, FormMethod.Post))

由于IEnumerable<SelectListItem> States无法以很好的方式解析查询字符串,因此表单操作将是Accounts/Create?StateId=0&States=System.Web.Mvc.SelectList并且模型绑定器将尝试将字符串“System.Web.Mvc.SelectList”绑定到一个IEnumerable<>,这就是您的代码不起作用的原因.

你可能会没事的

@using (Html.BeginForm())

,但如果你想指定动作,控制器和方法去

@using (Html.BeginForm("Create", "Accounts", FormMethod.Post))
于 2013-10-17T19:52:56.470 回答