本文介绍了如何绑定一个自定义类型的集合(IEnumerable的)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下动作,以显示与3项形式:

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

和则POST操作

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

修改
我查看看起来是这样的:

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

当我发布,我可以看到字段张贴在的Request.Form对象例如的Request.Form [全名]将显示:小贝,亨利。 赫尔南德斯Fergurson,这是我在表单中输入的值。 但是,中邮行动,为朋友的值总是空。的ReferAFriendModel有三个公共属性标识,EmailAddress的全名和

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.

我在做什么错了?

推荐答案

您可以看一看的following博客文章了解线格式数组和字典。我个人一直使用编辑器模板我的看法这需要产生输入字段的专有名称,以便默认模型绑定能够正确绑定值的照顾。

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" />
}

和在相应的编辑模板(〜/查看/共享/ EditorTemplates / ReferAFriendModel.cshtml

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

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

这篇关于如何绑定一个自定义类型的集合(IEnumerable的)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 00:36