Problem binding selected value to DropDownListFor inside Editor Template

允我心安 提交于 2019-12-25 08:26:03

问题


Description

I have a payment page that includes a form for entering bank account information. I have encapsulated the bank account information into a Model / Editor Template. The page itself has its own View Model, which happens to contain a BankAccount property to be passed in to the Editor.

[[View Models]]

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

[[Payment Page HTML]]

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

[[Editor Template]

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

Problem

Initially, this worked perfectly when I was strongly-typing the Payment page directly to the BankAccount model. The dropdown list was being populated properly, and the correct value from the model was being selected.

I recently modified the page, strongly-typing it to the PaymentPageModel, which contains the BankAccount model as a property. The HTML has not been modified. The result now, is that all the HTML values in the Editor Template are being populated properly, except for the DropDownList. It is binding the list of values properly from the BankAccountTypes select list, but the selected value is NOT being bound. I have checked to make sure that the value it is supposed to be binding to IS set properly by outputting it right next to the DropDownList.

This is driving me nuts, and is making me really question the reliability of Model binding and HTML Helpers in general, especially if I am unable to combine complex view models with Editor Templates to encapsulate presentation/functionality.

Any suggestions are greatly appreciated.


回答1:


If you have strongly typed the editor template to PaymentPageModel in your main view instead of:

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

you could try:

<%: Html.EditorForModel() %>

and in your editor template:

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


来源:https://stackoverflow.com/questions/3979191/problem-binding-selected-value-to-dropdownlistfor-inside-editor-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!