How to select an initial value for a DropDownList in MVC3 App






3.40/5 (4 votes)
How to select an initial value for a DropDownList in MVC3 App
In MVC3/.NET4.0/VS2010 web application, selecting a default value for an extension method -
DropDownList
or DropDownListFor
is tricky.
The DropDownList
first parameter should be any valid name other than the list instance name.
For example, you can have DropDownList("xyz",...)
not DropDownList("CompaniesRef",...)
, for the below example, when Model.CompaniesRef
instance is used to populate the list.
Same rule applies to DropDownListFor()
method too. For DropDownListFor(m=>m.Name,..)
, make sure the "m.Name
" (actually Name
) is any public
"string
" property in Model
class.
See the example below:
PersonView.cshtml
<table>
@model MyTestApp.Models.PersonAddressModel
<tr>
<!-- DONOT SELECT "HP" FROM THE LIST, INSTEAD SELECTS THE FIRST ITEM-->
<td>@Html.DropDownList("CompaniesRef", new SelectList(
Model.CompaniesRef,"Key","Value","HP"))
</td>
<td>@Html.DropDownListFor(m=>m.CompaniesRef, new SelectList(
Model.CompaniesRef,"Key","Value","HP"))
</td>
<!-- SELECTs "HP" FROM THE LIST. THIS IS CORRECT BEHAVIOR -->
<td>@Html.DropDownList("CompaniesRef_", new SelectList(
Model.CompaniesRef,"Key","Value","HP"))
</td>
<td>@Html.DropDownListFor(m=>m.Name, new SelectList(
Model.CompaniesRef,"Key","Value","HP"))
</td>
</tr>
</table>
Model class
class Person
{
public KeyValuePair<string, string>[] CompaniesRef { get; set; }
public string Name {get;set;}
public void Load()
{
CompaniesRef = new KeyValuePair<string, string>[]
{
new KeyValuePair<string, string>("MSFT", "Microsoft"),
new KeyValuePair<string, string>("IBM", "IBM"),
new KeyValuePair<string, string>("HP", "HP"),
new KeyValuePair<string, string>("GOOG", "Google"),
new KeyValuePair<string, string>("BOA", "BANK OF AMERICA"),
new KeyValuePair<string, string>("AMC", "American Airlines")
};
}
}
Controller method
public class PersonController : Controller
{
public ActionResult Person(Person p)
{
p.Load();
return View("PersonView",p);
}
}