Setting the selected option in MVC3
TagHelper
doesn't support C# code in its tag area.
However you can turn an option
element into a regular html tag using the !
character.
For example:
<!option @(ViewBag.CurrrentPage == x ? "selected" : "")>@x<!/option>
Something like:
int selectedOption = ViewBag.SelectedOption;
<select id="SelectedYear" name="SelectedYear">
<option value="2010" @(selectedOption == 2010 ? "selected" : "")>2010</option>
<option value="2011" @(selectedOption == 2011 ? "selected" : "")>2011</option>
<option value="2012" @(selectedOption == 2012 ? "selected" : "")>2012</option>
<option value="2013" @(selectedOption == 2013 ? "selected" : "")>2013</option>
</select>
That being said, this is the kind of stuff HtmlHelper.DropDownList is for.
Have your logic inside the controller and just pass an IEnumerable through ViewBag. At that point you just have to call the helper within the view:
@Html.DropDownList("optionName", ViewBag.MyOptionsList as IEnumerable<SelectListItem>)