Dr.*_*ite 2 c# asp.net-mvc binding list
我一直在尝试将视图绑定到对象列表,如此处所述模型绑定到列表
我的问题是当列表通过POST返回时,列表包含我最初发送的正确数量的元素,但对象中的值将返回,就好像它们从未设置过一样.不确定我错过了什么使模型绑定器正确解析.
这是我的测试代码:
我的模型是:
IList<Test>
Run Code Online (Sandbox Code Playgroud)
其中Test定义为:
public class Test
{
public int x;
}
Run Code Online (Sandbox Code Playgroud)
在我的TestController中,我使用的方法是"Create",它有一个回发:
public ActionResult Create()
{
List<Models.Test> testList = new List<Models.Test>() {
new Models.Test() { x = 5 }
};
return View(testList);
}
//
// POST: /Test/Create
[HttpPost]
public ActionResult Create(IList<Models.Test> tests)//Models.TestContainer tc)
{
return View(tests);
}
Run Code Online (Sandbox Code Playgroud)
和"创建"视图的代码:
@model IList<ksg.Models.Test>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>TestContainer</legend>
@Html.EditorFor(x => x[0])
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
Run Code Online (Sandbox Code Playgroud)
最后,我的Test类的编辑器模板:
@model ksg.Models.Test
@using ksg.Helpers
<div>
@Html.TextBoxFor(x => x.x)
</div>
Run Code Online (Sandbox Code Playgroud)
如上所示,我发送一个包含1个项目的列表Test.x = 5,但是当我打开断点时 Create(IList<Models.Test> tests),测试包含1个对象x = 0.
我错过了什么想法?
试试这2个变化:
测试类:
public class Test
{
public int x { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
Create.cshtml
@using (Html.BeginForm())
{
@Html.ValidationSummary(true)
<fieldset>
<legend>TestContainer</legend>
@Html.EditorFor(x => x[0].x) @*<--*@
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
Run Code Online (Sandbox Code Playgroud)