【问题标题】:Problem binding selected value to DropDownListFor inside Editor Template将选定值绑定到编辑器模板内的 DropDownListFor 的问题
【发布时间】:2010-10-20 14:53:52
【问题描述】:

说明

我有一个付款页面,其中包含用于输入银行帐户信息的表单。我已将银行帐户信息封装到模型/编辑器模板中。页面本身有自己的视图模型,其中恰好包含要传递给编辑器的 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) %>
...

问题

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

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

这让我发疯了,让我真的怀疑模型绑定和 HTML 助手的可靠性,尤其是当我无法将复杂的视图模型与编辑器模板结合起来以封装表示/功能时。

非常感谢任何建议。

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-2 html-helper mvc-editor-templates


    【解决方案1】:

    如果您在主视图中将编辑器模板强输入为PaymentPageModel,而不是:

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

    你可以试试:

    <%: Html.EditorForModel() %>
    

    在您的编辑器模板中:

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

    【讨论】:

    • 感谢您的建议。我会试一试的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-13
    • 2011-12-01
    相关资源
    最近更新 更多