How do I Bind a Collection (IEnumerable) of a custom type?

杀马特。学长 韩版系。学妹 提交于 2019-12-04 20:57:14

问题


I have the following Action to display a form with 3 items :

[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);
    }

and then a Post action

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

EDIT My View looks like this:

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

The partial looks like this:

@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>

When I post, I can see the fields are posted in the Request.Form object e.g Request.Form["FullName"] will show: "David Beckham","Thierry Henry". "Chicharito Fergurson" which are the values I entered in the form. But, the in the Post action,the value for 'friends' is always null. The ReferAFriendModel has three public properties Id, EmailAddress and FullName.

What am I doing wrong?


回答1:


You may take a look at the following blog post about the wire format for arrays and dictionaries. Personally I always use editor templates in my views which take care of generating proper names of the input fields so that the default model binder is able to bind the values correctly.

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

and in the corresponding editor template (~/Views/Shared/EditorTemplates/ReferAFriendModel.cshtml):

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


来源:https://stackoverflow.com/questions/6212837/how-do-i-bind-a-collection-ienumerable-of-a-custom-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!