asp.net mvc – Problem binding selected value to DropDownListFor inside Editor Template – Education Career Blog

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.

,

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) %>

Leave a Comment