在razor MVC 4的下拉列表中选择一个值

时间:2013-05-01 19:45:25

标签: asp.net-mvc razor html-select

如何在模型对象数组中的Razor中设置DropdownList的选定值?例如:

@foreach (var model in Model.Courses)
{
   ....
   <td>
       @Html.DropDownList(**** set the selected value from model.Order, from my Model.Positions list ****)
   </td>
   ....
}

谢谢!

2 个答案:

答案 0 :(得分:4)

试试这个

@foreach (var model in Model.Courses)
{
   ....
   <td>
                          //Control Name,  Options,     Selected Value
       @Html.DropDownList("NameOfControl", ListOfItems, model.Value)
   </td>
   ....
}

答案 1 :(得分:1)

最好尝试使用SelectList

在数据源本身中设置所选选项
    Dictionary<string, string> list = new Dictionary<string, string>();
    list.Add("Value1", "1");
    list.Add("Value2", "2");
    list.Add("Value3", "3");
    var selectList = new SelectList(list,
              "Value", "Key", 
              "2"); // selected item's value "Value2" is selected.
    ViewData["SelectedValue"] = selectList;

    @Html.DropDownList("ddlValues", (SelectList)ViewData["SelectedValue"]) )