代码之家  ›  专栏  ›  技术社区  ›  dotariel

将选定值绑定到编辑器模板内的DropDownList时出现问题

  •  0
  • dotariel  · 技术社区  · 14 年前

    描述

    我有一个付款页面,其中包含一个用于输入银行帐户信息的表单。我已将银行帐户信息封装到模型/编辑器模板中。页面本身有自己的视图模型,该模型恰好包含要传递给编辑器的BankAccount属性。

    [视图模型]

    public class PaymentPageModel { 
        public SomeProperty1 { get; set; }
        public SomeProperty2 { get; set; }
        public BankAccount BankAccount { get; set; }
        ...
    }
    
    public class BankAccount { 
        public int BankAccountTypeID { get; set; }
        public string BankName { get; set; }
        public string ABACode { get; set; }
        public string AccountNumber { get; set;}
        public IEnumerable<SelectListItem> BankAccountTypes {
            get { ... // Constructs the list }
        }
    }
    

    [[付款页html]]

    <% using (Html.BeginForm()) { %>
    <%: Html.EditorFor(m => m.BankAccount) %>
        ... // Other miscellaneous stuff not related to the actual BankAccount
    <% } %>
    

    [[编辑器模板]

    ...
    <%: Html.DropDownListFor(m => m.BankAccountTypeID, Model.BankAccountTypes) %>
    ...
    

    问题

    最初,当我强烈地将付款页面直接输入到银行帐户模型时,这非常有效。正在正确填充下拉列表,并且正在选择模型中的正确值。

    我最近修改了页面,强烈地将其键入paymentpagemodel,其中包含作为属性的银行帐户模型。尚未修改HTML。现在的结果是编辑器模板中的所有HTML值都被正确填充,DropDownList除外。它正在从BankAccountTypes选择列表中正确绑定值列表,但未绑定所选值。我已经检查过了,确保它应该绑定到的值是通过将其输出到DropDownList旁边正确设置的。

    这让我抓狂,使我对模型绑定和HTML帮助程序的可靠性产生了疑问,尤其是当我无法将复杂的视图模型与编辑器模板结合起来来封装表示/功能时。

    任何建议都非常感谢。

    1 回复  |  直到 14 年前
        1
  •  0
  •   Darin Dimitrov    14 年前

    如果已将编辑器模板强键入到 PaymentPageModel 在主视图中,而不是:

    <%: Html.EditorFor(m => m.BankAccount) %>
    

    你可以试试:

    <%: Html.EditorForModel() %>
    

    在编辑器模板中:

    <%: Html.DropDownListFor(m => m.BankAccount.BankAccountTypeID, 
        Model.BankAccount.BankAccountTypes) %>