kar*_*una 8 html forms post model-binding asp.net-mvc-3
这是我的模型:
public class Items
{
public string Foo { get; set; }
public string Bar { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
控制器:
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);
}
Run Code Online (Sandbox Code Playgroud)
查看(索引):
@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>
}
Run Code Online (Sandbox Code Playgroud)
我删除了第二对:
<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>
Run Code Online (Sandbox Code Playgroud)
发布时,我只获得第一对("foo"和"bar").这是因为第三对有索引"2".我想得到两个对(不使用FormCollection.我希望它自动绑定).实际上,我在表单上有很多其他输入,所以我不想重新加载并重新附加每个输入的索引.你能帮助我吗?
我找到了解决方案,感谢 Amit Prajapati:
@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>
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7529 次 |
| 最近记录: |