Setting the selected option in MVC3

So I can go this far

string selectedOption = ViewBag.SelectedOption; <select id="SelectedYear" name="SelectedYear"> <option value="2010">2010</option>//if(selectedOption == 2010)...meh... <option value="2011">2011</option> <option value="2012">2012</option> <option value="2013">2013</option> </select> 

And I know that I can store SelectedOption in a div and set the selected option using jQuery in a compressed form after $(document).ready .

Is there a short method for doing a task with a direct MVC3 / razor?

+8
asp.net-mvc-3 razor
source share
3 answers

Something like:

 int selectedOption = ViewBag.SelectedOption; <select id="SelectedYear" name="SelectedYear"> <option value="2010" selected="@(selectedOption == 2010 ? "selected" : "")">2010</option> <option value="2011" selected="@(selectedOption == 2011 ? "selected" : "")">2011</option> <option value="2012" selected="@(selectedOption == 2012 ? "selected" : "")">2012</option> <option value="2013" selected="@(selectedOption == 2013 ? "selected" : "")">2013</option> </select> 

That being said, this is the HtmlHelper.DropDownList material for.

Have your logic inside the controller and just pass IEnumerable through the ViewBag. At this point, you just need to call an assistant in the view:

 @Html.DropDownList("optionName", ViewBag.MyOptionsList as IEnumerable<SelectListItem>) 
+14
source share
 int selectedOption = ViewBag.SelectedOption; <select id="SelectedYear" name="SelectedYear"> <option value="2010" @if(selectedOption == 2010){<text>selected="selected"</text>}>2010</option> ... </select> 
+7
source share

The method that answered the correct question does not work now, it is better to use the following example:

 <option value="someValie" @(ViewBag.someVariable == "someValue" ? "selected" : String.Empty)>...</option> 
+4
source share

All Articles