ASP.Net MVC3 Parent Child Model Binding

僤鯓⒐⒋嵵緔 提交于 2019-12-24 09:56:12

问题


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)

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?


回答1:


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" />
...

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:

ASP.NET MVC: Binding a Complex Type to a Select




回答2:


Use Editor Templates instead of a partial view - no need to hard code your indexes as the template will automagically index all your objects correctly, even when you add and remove Accounts. See my answer to this question:

Pass values from multiple partial views

Small write up on Editor Templates here:

codenodes.wordpress.com - MVC3 Editor Templates



来源:https://stackoverflow.com/questions/5623366/asp-net-mvc3-parent-child-model-binding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!