rob*_*sta 7 c# asp.net-mvc model-binding razor asp.net-mvc-3
我有以下操作来显示包含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.
我究竟做错了什么?
您可以查看以下关于数组和字典的有线格式的博客文章.我个人总是在视图中使用编辑器模板,它们负责生成输入字段的正确名称,以便默认模型绑定器能够正确绑定值.
@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)
...
| 归档时间: | 
 | 
| 查看次数: | 11438 次 | 
| 最近记录: |