麻烦绑定到MVC3列表 [英] Trouble Binding to a List in MVC3

查看:110
本文介绍了麻烦绑定到MVC3列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在试图将视图绑定到对象的列表在这里所描述的模型绑定到一个列表

I've been attempting to bind a view to a list of objects as described here Model Binding To A List

我的问题是,当通过POST返回列表,列表中包含了我最初发送元素的正确数目,但对象中的值都回来了,好像他们从来没有被设置。不知道我错过了做模型绑定正确解析。

My problem is when the list is returned via a POST, the list contains the correct number of elements that I originally sent, but the values within the objects are coming back as if they were never set. Not sure what I missed to make the model binder parse correctly.

下面是我的测试code:

Here is my test code:

我的模式是:

IList<Test>

,其中测试的定义是:

where Test is defined as:

public class Test
{
    public int x;
}

在我的TestController,我使用的方法创建其中有一个回送:

In my TestController, I am using a method "Create" which has a postback:

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

和创建视图的code:

and the "Create" view's code:

@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类编辑模板:

And finally, my editor template for the Test class:

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

如上图所示,我送的列表,包括1项与 Test.x = 5 ,但是当我断点创建(IList的&LT;模型。测试&GT;测试),测试包含 X = 0

As shown above, I send a list with 1 item with Test.x = 5, but when I breakpoint on Create(IList<Models.Test> tests), tests contains 1 object with x = 0.

任何想法我错过了吗?

推荐答案

我想你的code和问题是, X 测试类的<​​strong>字段和不是财产,因此默认模式粘结剂不能设置从提交的表单值。 测试类应该是这样的:

I have tried your code and problem is that x in Test class is field and not property, thus the default model binder cannot set value from posted form. Test class should look like this:

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

然后,它的工作原理。

Then it works.

这篇关于麻烦绑定到MVC3列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆