2012-09-06 50 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> 
}