【问题标题】:ASP.NET MVC: Binding dynamically rendered partial views as nested properties of the view modelASP.NET MVC:将动态呈现的部分视图绑定为视图模型的嵌套属性
【发布时间】:2014-01-15 14:30:15
【问题描述】:

我有以下视图模型:

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

在我的单一视图中,我有一个绑定 Person 模型的表单,还有一个 DropDownList 让用户选择帐户类型。

一旦用户做出选择,我会使用 jQuery ajax 动态加载代表BankAccountPayPalAccount 的部分视图之一,并将其​​添加到页面中。

用户点击提交后,我调用这个动作:

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
}

如何使部分视图属性绑定到我的Person 视图模型中的嵌套属性?

【问题讨论】:

    标签: c# asp.net asp.net-mvc-4 jquery data-binding


    【解决方案1】:

    您的表单字段必须带有前缀(BankAccount.PayPalAccount.),以便它们可以自动绑定。

    当您从 Ajax 返回局部视图时,使用当前使用的模型,它们的名称没有前缀。

    为它们添加前缀的更简单方法是对两个局部视图使用完全相同的 View Model 类:Person。如果你这样做,你必须在 Razor 中写

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

    生成的输入字段将具有所需的前缀BankAccount.,即它看起来像这样:<input ... name='BankAccount.BankName' ... />

    您也可以为您的局部视图创建这样的视图模型:

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

    最后,您可以尝试这样的解决方案: ASP.NET MVC partial views: input name prefixes

    我不能保证最后一个解决方案会正常工作:例如,它可能会破坏ModelState。而且更难实施且“标准较低”。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-24
      • 2023-03-06
      • 1970-01-01
      • 2015-04-14
      • 1970-01-01
      相关资源
      最近更新 更多