Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting the selected option in MVC3

So I can get 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 I can store SelectedOption in a div and set the selected option with jQuery in a concise way after $(document).ready.

Is there a concise method to accomplish the task with straight up MVC3/razor?

like image 598
P.Brian.Mackey Avatar asked Oct 07 '11 21:10

P.Brian.Mackey


People also ask

How can I change the selected value of a DropDownList using jquery?

Using the jQuery change() method; you can set the selected value of dropdown in jquery by using id, name, class, and tag with selected html elements; see the following example for that: Example 1 :- Set selected value of dropdown in jquery by id.


1 Answers

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>)
like image 71
Joao Avatar answered Nov 15 '22 20:11

Joao