2011-06-02 73 views
7

我有下列行動3項顯示錶單:如何綁定自定義類型的集合(IEnumerable)?

[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」,這是我在表格中輸入的值。 但是,在「發佈」操作中,「朋友」的值始終爲空。 ReferAFriendModel有三個公共屬性Id,EmailAddress和FullName。

我在做什麼錯?

+0

可能出錯了你的表單/視圖。你應該顯示該代碼。 – RPM1984 2011-06-02 09:47:27

+0

[如何將IEnumerable列表傳遞給MVC中的控制器,包括複選框狀態?](http://stackoverflow.com/questions/17037858/how-to-pass-ienumerable-list-to-controller-in-mvc-包括複選框狀態) – abatishchev 2016-08-27 20:13:49

回答

9

您可以查看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) 
... 
+2

正是我想要的,我使用的是一個MVC2教程,導致我走錯了路。謝謝 – robasta 2011-06-02 10:10:34

相關問題