DropDownList SelectedValue has no required binding
I have a DropDownList filled with a SelectList generated from (anonymous type) that has two properties, "CountryId" (int) and "Description" (string). I want the selected country in the list to be defaultCountry.
Countries = new SelectList(countries, "CountryId", "Description", defaultCountry.CountryId);
where "countries" is the IQueryable of the anonymous types from the Linq query. Countries are public property on the presentation model:
public class CountryBaseViewModel
{
public SelectList Countries { get; set; }
public Contact Contact { get;set; }
....
}
HTML looks like this:
<p>
<label for="CountryId">Home Country:</label>
<%= Html.DropDownList("CountryId", Model.Countries)%>
</p>
This is ok and when I load the page the correct country is selected.
But when I pass the change to the Edit method on the controller, the binding seems to fail.
For example, when I use the following HTML
<p>
<label for="Contact.Job">Job/Post:</label>
<%= Html.TextBox("Contact.Job", Model.Contact.Job) %>
</p>
And I call the method
public ActionResult Create(Contact contact)
on the controller, then the contact.Job value is correctly populated from the TextBox, but the CountryId is not.
I am assuming MVC is using the "Contact.Job" parameter (TextBox 1st) to set this. But the first parameter of the DropDownList is "CountryId", not "Contact.CountryId", because if it is, then the selected value is not shown in the list when it is loaded.
It looks like the first parameter of the TextBox is for data binding and the first parameter of the DropDownList is to find the selected item.
How do I use this data binding style to get the selected value I want in a DropDownList and then bind it to Model.Contact.Country?
a source to share
You need to bind the selected value from the dropdown manually by searching for whatever object you actually need to bind in your controller action that is called in the POST. You can use a strongly typed value in your ViewModel as suggested in the second post, or you can find the dropdown value in the ViewData bag.
So, you have most of everything in place, but in your controller action that is handling POST, you will want to get the dropdown value, load the object associated with that value, and then attach that object to the object you are trying to update. Depending on your architecture, this is often just a call to the repository or data access service. You must do this binding manually before saving changes to the main object you are working with.
a source to share