c# - 无法绑定(bind)到 MVC3 中的列表

标签 c# asp.net-mvc list binding

我一直在尝试将 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/

相关文章:

asp.net-mvc - 我如何不允许对我的 Web 应用程序进行任何 Firefox 自定义?

asp.net-mvc - ASP.NET 成员(member) : Custom Profile Inheritance

java - 结果集为 List<Product> 和 List<Map<String, String>>

python - 将列表列表转换为 float ,同时忽略字符串列

c# - 这个 C# 语法有什么作用?

c# - Microsoft ADD - 应用程序注册 - 请求中指定的回复网址与配置的回复网址不匹配

c# - C# 中的 Struct.Pack 等价物?

c# - SQL 表根据带有存储过程的 IF 语句从另一个表获取信息

json - 在 mvc 中创建 json 对象并从 Controller 返回

python - 根据键重新排列列表而不排序