Setting the selected option in MVC3

帅比萌擦擦* 提交于 2019-12-21 04:21:07

问题


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?


回答1:


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 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>)



回答2:


int selectedOption = ViewBag.SelectedOption;


<select id="SelectedYear" name="SelectedYear"> 

<option value="2010" @if(selectedOption == 2010){<text>selected="selected"</text>}>2010</option>

...

</select>



回答3:


The method, answered in the correct question is not working for now, it's better to use the next example:

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



回答4:


TagHelper doesn't allow the C# code in their tag area.

You can turn an option element into a regular html tag by using the character !.

For example:

<!option @(ViewBag.CurrrentPage == x ? "selected" : "")>@x<!/option>


来源:https://stackoverflow.com/questions/7693083/setting-the-selected-option-in-mvc3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!