ASP.Net MVC3 父子模型绑定
我有一个使用 User 对象作为模型的部分模板。用户拥有一个帐户集合。在此部分模板上,我有一个循环,如下所示。 _Account 部分模板绑定到 Account 类
@foreach (var item in Model.Accounts)
{
<tr>
<td colspan="6">
<div>
@Html.Partial("_Account", item)
</div>
</td>
</tr>
}
在我的控制器方法中,我最初尝试过
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult UserDetails(User user, string actionType)
,但 User.Accounts 集合是空的。然后我尝试了这个。 Accounts 集合仍然是空的。
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult UserDetails(User user,
[Bind(Prefix="User.Accounts")]
FixupCollection<Account> Accounts,
string actionType)
我可以使用默认的 Modelbinder 实现来实现此目的还是需要做任何不同的事情?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,您可以使用默认的模型绑定器。您只需要正确命名您的字段即可。因此,您需要循环输出如下内容:
如果您需要添加/删除帐户,则硬编码索引会变得有点棘手。您可以在回发之前使用 javascript 重新分配名称。但这一切都有可能。这个问题提供了有关模型绑定的更多详细信息:
ASP.NET MVC:将复杂类型绑定到选择
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:
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
使用编辑器模板而不是部分视图 - 无需对索引进行硬编码,因为模板会自动正确地为所有对象建立索引,即使您添加和删除帐户也是如此。请参阅我对此问题的回答:
从多个部分视图传递值
此处编辑器模板的小写:
codenodes.wordpress.com - MVC3 编辑器模板
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