在设置MVC3选择的选项 [英] Setting the selected option in MVC3

查看:97
本文介绍了在设置MVC3选择的选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此​​,我可以走这么远。<​​/ P>

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>

我知道 SelectedOption 我可以存储在 DIV 并以简洁的方式使用jQuery选择的选项设置在 $(文件)。就绪

And I know I can store SelectedOption in a div and set the selected option with jQuery in a concise way after $(document).ready.

有没有做到与直线上升MVC3 /剃刀任务的一个简洁的方法?

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

推荐答案

是这样的:

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>

话虽这么说,这是什么样的东西 HtmlHelper.DropDownList 是为

有控制器内你的逻辑和刚刚经历的 ViewBag 的传递的的IEnumerable 的。在这一点上,你只需要调用视图中的助手:

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

这篇关于在设置MVC3选择的选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆