ASP.Net MVC3亲子模型绑定 [英] ASP.Net MVC3 Parent Child Model Binding

查看:204
本文介绍了ASP.Net MVC3亲子模型绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用用户对象模型的局部模板。用户拥有帐户的集合。在这个局部模板我有一个循环如下。该_account局部模板被绑定到Account类

I have a partial template that uses a User object as a model. The user has a collection of Accounts. On this partial template I have a loop as follows. The _Account partial template is bound to the Account class

  @foreach (var item in Model.Accounts)
            { 
                <tr>
                    <td colspan="6">
                        <div>
                            @Html.Partial("_Account", item)
                        </div>
                    </td>
                </tr>

            }

在我的控制器方法我最初尝试

In my controller method I initially tried

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult UserDetails(User user, string actionType)

但User.Accounts集合为空。然后我尝试这一点。尽管如此帐户集合为空。

But the User.Accounts collection is empty. Then I tried this. Still the Accounts collection is empty.

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult UserDetails(User user,  
                             [Bind(Prefix="User.Accounts")]
                             FixupCollection<Account> Accounts, 
                             string actionType)

我可以使用默认的模型绑定器实现这个功能或做我需要做什么不同?

Can I use the default Modelbinder implementation to achieve this or do I need to do anything different?

推荐答案

是的,你可以使用默认的模型粘合剂。你只需要正确命名的字段。所以,你需要你的循环输出是这样的:

Yep, you can use the default model binder. You just need to name your fields correctly. So you need your loop to output something like this:

...
<input type="text" name="user.Accounts[0].SomeTextField" />
<input type="text" name="user.Accounts[0].SomeOtherTextField" />
...
<input type="text" name="user.Accounts[1].SomeTextField" />
<input type="text" name="user.Accounts[1].SomeOtherTextField" />
...

如果您需要添加/删除帐户,硬codeD索引变得有点棘手。你可以重新分配使用javascript回发前的名称。但是,这一切成为可能。这个问题给出了模型绑定更多详细信息:

If you need to add/remove accounts, the hardcoded indexes get a little trickier. You could re-assign the names using javascript before postback. But it's all possible. This question gives more detail on model binding:

<一个href=\"http://stackoverflow.com/questions/554790/asp-net-mvc-binding-a-complex-type-to-a-select\">ASP.NET MVC:绑定复杂类型到选择

这篇关于ASP.Net MVC3亲子模型绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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