2012-09-06 48 views
8

這裏是我的模型:ASP.NET MVC型號列表綁定

public class Items 
    { 
     public string Foo { get; set; } 
     public string Bar { get; set; } 
    } 

控制器:

public ActionResult Index() 
    { 
     var model = new List<Items> 
         { 
          new Items 
           { 
            Foo = "foo", 
            Bar = "bar" 
           }, 
          new Items 
           { 
            Foo = "ai", 
            Bar = "ia" 
           }, 
          new Items 
           { 
            Foo = "one", 
            Bar = "two" 
           } 
         }; 
     return View(model); 
    } 

    [HttpPost] 
    public ActionResult Index(List<Items> model) 
    { 
     return View(model); 
    } 

視圖(指數):

@using (Html.BeginForm()) 
{ 
    for (int i = 0; i < Model.Count; i++) 
    { 
     <div onclick="$(this).remove();"> 
      @Html.TextBoxFor(model => model[i].Foo) <br/> 
      @Html.TextBoxFor(model => model[i].Bar) 
     </div> 
    } 
    <div> 
     <input type="submit"/> 
    </div> 
} 

我刪除第二對:

<div onclick="$(this).remove();"> 
     <input name="[0].Foo" type="text" value="foo"> <br> 
     <input name="[0].Bar" type="text" value="bar"> 
    </div> 

    <div onclick="$(this).remove();"> 
     <input name="[2].Foo" type="text" value="one"> <br> 
     <input name="[2].Bar" type="text" value="two"> 
    </div> 

發帖時,我只得到第一對(「foo」和「bar」)。這是因爲第三對索引爲「2」。我想得到兩個對(不使用FormCollection,我希望它自動綁定)。實際上,我在表單上有很多其他輸入,因此我不想重新加載並重新附加索引到每個輸入。你可以幫我嗎?

+0

您是否檢查過生成的HTML並驗證了預期的輸入字段在表單的範圍內? –

+0

我已經發布生成的HTML和是的,它是在窗體內。請參閱「我刪除第二對:」部分 – karaxuna

回答

3

我找到了解決方案,這要歸功於阿米特生主:

@using (Html.BeginForm()) 
{ 
    for (int i = 0; i < Model.Count; i++) 
    { 
     var identifier = Guid.NewGuid(); 
     <div onclick="$(this).remove();"> 
      @Html.Hidden("Index", identifier) 
      @Html.TextBox("[" + identifier + "].Foo") 
      <br/> 
      @Html.TextBox("[" + identifier + "].Bar") 
     </div> 
    } 
    <div> 
     <input type="submit" /> 
    </div> 
}