【问题标题】:How do I Bind a Collection (IEnumerable) of a custom type?如何绑定自定义类型的集合(IEnumerable)?
【发布时间】:2011-06-02 09:45:08
【问题描述】:

我有以下操作来显示一个包含 3 个项目的表单:

[HttpGet]
    public ActionResult ReferAFriend()
    {
        List<ReferAFriendModel> friends = new List<ReferAFriendModel>();
        ReferAFriendModel f1 = new ReferAFriendModel();
        ReferAFriendModel f2 = new ReferAFriendModel();
        ReferAFriendModel f3 = new ReferAFriendModel();

        friends.Add(f1);
        friends.Add(f2);
        friends.Add(f3);
        return View(friends);
    }

然后是 Post 操作

[HttpPost]
    public ActionResult ReferAFriend(IEnumerable<ReferAFriendModel> friends)
    {
        if(ModelState.IsValid){

编辑 我的视图如下所示:

@model IEnumerable<Models.ReferAFriendModel>
@for(int i=0;i<Model.Count();i++)
    {
        @Html.Partial("_ReferAFriend", Model.ElementAt(i));
    }

部分看起来像这样:

@model Models.ReferAFriendModel
<p>
   @Html.LabelFor(i => i.FullName) @Html.TextBoxFor(i => i.FullName)<br />
   @Html.LabelFor(i => i.EmailAddress) @Html.TextBoxFor(i => i.EmailAddress)
   @Html.HiddenFor(i=>i.Id)
</p>

当我发布时,我可以看到在 Request.Form 对象中发布的字段,例如 Request.Form["FullName"] 将显示:"David Beckham","Thierry Henry"。 “Chicharito Fergurson”,这是我在表格中输入的值。 但是,在 Post 操作中,'friends' 的值始终为 null。ReferAFriendModel 具有三个公共属性 Id、EmailAddress 和 FullName。

我做错了什么?

【问题讨论】:

标签: c# asp.net-mvc asp.net-mvc-3 razor model-binding


【解决方案1】:

您可以查看following blog post 关于数组和字典的有线格式。就我个人而言,我总是在我的视图中使用编辑器模板,这些模板负责生成输入字段的正确名称,以便默认模型绑定器能够正确绑定值。

@model IEnumerable<ReferAFriendModel>
@using (Html.BEginForm())
{
    @Html.EditorForModel()
    <input type="submit" value="OK" />
}

并在相应的编辑器模板中(~/Views/Shared/EditorTemplates/ReferAFriendModel.cshtml):

@model ReferAFriendModel
@Html.EditorFor(x => x.Prop1)
@Html.EditorFor(x => x.Prop2)
...

【讨论】:

  • 正是我想要的,我使用的是 MVC2 教程,导致我走错了路。谢谢
猜你喜欢
  • 1970-01-01
  • 2011-02-22
  • 2012-07-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-08
相关资源
最近更新 更多