我一直在尝试将 View 绑定(bind)到对象列表,如此处所述 Model Binding To A List
我的问题是当通过 POST 返回列表时,列表包含我最初发送的正确数量的元素,但是对象中的值返回时就像它们从未设置过一样。不确定我错过了什么让模型 Binder 正确解析。
这是我的测试代码:
我的模型是:
IList<Test>
其中测试定义为:
public class Test
{
public int x;
}
在我的 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);
}
和“创建” View 的代码:
@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>
}
最后,我的测试类编辑器模板:
@model ksg.Models.Test
@using ksg.Helpers
<div>
@Html.TextBoxFor(x => x.x)
</div>
如上所示,我发送了一个包含 1 个项目的列表 Test.x = 5
, 但是当我在 Create(IList<Models.Test> tests)
上断点时,测试包含 1 个对象 x = 0
.
有什么我遗漏的想法吗?
最佳答案
尝试这 2 项更改:
测试类:
public class Test
{
public int x { get; set; }
}
创建.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>
}
关于c# - 无法绑定(bind)到 MVC3 中的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14150658/