Reputation: 9279
I have a C#.Net MVC 3 web app and need to implement a year date drop down set similar to what is used on a credit card site for expiration date. Select a month, then select a day. I want to default to a value that is set in the web config file. How do I set a default value for a drop down?
Upvotes: 0
Views: 574
Reputation: 14133
Controller
var yearlist = new[] {
new MyYear { Id = 2011, Text = "2011" },
new MyYear { Id = 2010, Text = "2010" },
new MyYear { Id = 2009, Text = "2009" },
new MyYear { Id = 2008, Text = "2008" }
};
var selectList = new SelectList(yearlist , "Id", "Text", 2011);
ViewData["Years"] = selectList;
The SelectList last parameter is the id that you want to get from the web.config and be selected by default.
View
@Html.DropDownList("YearClass", (SelectList)ViewData["Years"])
Upvotes: 2
Reputation: 46008
Use SelectList - you can specify selected value in the constructor.
Pass SelectList
instance to view, it works with Html.DropDown
extension methods.
Upvotes: 1