ASP.NET MVC:绑定动态呈现局部视图作为视图模型嵌套的属性 [英] ASP.NET MVC: Binding dynamically rendered partial views as nested properties of the view model

查看:114
本文介绍了ASP.NET MVC:绑定动态呈现局部视图作为视图模型嵌套的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下视图模型:

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public BankAccount BankAccount { get; set; }
    public PayPalAccount PayPalAccount { get; set; }
}

public class BankAccount
{
    public string BankName { get; set; }
    public string AccountNumber { get; set; }
}

public class PayPalAccount
{
    public string PayPalEmail { get; set; }
}

在我的单一视图我有一个绑定模式,还具有形式的DropDownList 这让我们的用户选择帐户类型。

In my single view I have a form that binds the Person model and also has a DropDownList that let's the user choose an account type.

一旦用户做出选择,我加载动态使用jQuery阿贾克斯的重新present无论是的BankAccount PayPalAccount ,我把它添加到页面。

Once the user makes his choice, I load dynamically using jQuery ajax one of the partial views that represent either the BankAccount or the PayPalAccount and I add it to the page.

在用户点击提交,我称这种动作:

After the user clicks submit, I call this action:

public ActionResult Save(Person person)
{ 
    // Here I expect that either person.BankAccount or person.PayPalAccount 
    // will contain the user input, and the other will be null
}

我如何使局部视图属性绑定到我的视图模型嵌套的财产?

推荐答案

您表单字段必须是prefixed(以的BankAccount。 PayPalAccount ),使得它们可以被自动绑定

Your form fields must be prefixed (with BankAccount. or PayPalAccount.) so that they can be automatically bound.

当您从阿贾克斯回报您的局部视图,withthe目前的模式你使用,他们的名字没有preFIX。

When you return your partial view from Ajax, withthe current model you're using, their names don't have a prefix.

要$ P $的更简单的方法PFIX他们使用完全相同的视图模型类:这两个部分景色。如果你做的是,在剃刀,你得写

The easier way to prefix them is using exactly the same View Model class: Person for both partial views. If you do that, in the Razor you'll have to write

@Html.EditorFor(m => m.BankAccount.BankName)

生成的输入字段将具有所需的preFIX 的BankAccount ,也就是说,它看起来就像这样:<输入...名称= BankAccount.BankName'... />

The generated input field will have the required prefix BankAccount., i.e. it will look like this: <input ... name='BankAccount.BankName' ... />

您还可以创建这样的视图模型为你的部分:

You could also create a view model like this for your partial:

public class BakAccountModel
{
   // make sure the property name is the same as in the Person view model
   public BankAccount { get; set; } 
}

这是最后,你可以尝试这样的解决方案:
<一href=\"http://stackoverflow.com/questions/1488890/asp-net-mvc-partial-views-input-name-$p$pfixes\">ASP.NET MVC局部视图:输入名称prefixes

An finally, you can try a solution like this: ASP.NET MVC partial views: input name prefixes

我不能保证最后的解决方案将正常工作:例如,它可能会破坏的ModelState 。而更难implemente和更少的标准。

I can't assure the last solution will work fine: for example it could break the ModelState. And is harder to implemente and "less standard".

这篇关于ASP.NET MVC:绑定动态呈现局部视图作为视图模型嵌套的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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