簡體   English   中英

如何綁定自定義類型的集合(IEnumerable)?

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

我有以下操作來顯示一個包含 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 object 例如 Request.Form["FullName"] 將顯示:"David Beckham","Thierry Henry"。 “Chicharito Fergurson”,這是我在表格中輸入的值。 但是,在 Post 操作中,“friends”的值始終是 null。 ReferAFriendModel 具有三個公共屬性 Id、EmailAddress 和 FullName。

我究竟做錯了什么?

您可以查看以下有關 arrays 和字典的電匯格式的博客文章 就個人而言,我總是在我的視圖中使用編輯器模板,這些模板負責生成輸入字段的正確名稱,以便默認的 model 綁定器能夠正確綁定值。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM