繁体   English   中英

麻烦绑定到MVC3中的列表

[英]Trouble Binding to a List in MVC3

我一直在尝试将视图绑定到对象列表,如此处所述将模型绑定到列表

我的问题是当列表通过POST返回时,列表包含我最初发送的正确数量的元素,但对象中的值将返回,就好像它们从未设置过一样。 不知道我错过了什么使模型联编程序正确解析。

这是我的测试代码:

我的模型是:

IList<Test>

其中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);
    }

以及“创建”视图的代码:

@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>
}

最后,我的Test类的编辑器模板:

@model ksg.Models.Test
@using ksg.Helpers
<div>
@Html.TextBoxFor(x => x.x)
</div>

如上所示,我发送一个包含Test.x = 5项目的列表,但是当我在Create(IList<Models.Test> tests)上断点时,测试包含1个x = 0对象。

有什么想法我错过了吗?

试试这2个变化:

测试类:

      public class Test
      {
         public int x { get; set; }
      }

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>
    }

我已经尝试过你的代码,问题是Test类中的x字段不是属性 ,因此默认的模型绑定器不能从发布的表单中设置值。 Test类应如下所示:

public class Test
{
    public int X {get; set;}
}

然后它工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM