13

在我的剃须刀中,我正在生成这样的下拉列表。

    @{
        var listItems = new List<ListItem> 
        { 
              new ListItem { Text = "Home To School", Value = "0" }, 
              new ListItem { Text = "School To Home", Value = "1" } 
        };
    }

@Html.DropDownList("Direction", new SelectList(listItems),new {onchange = "getAlldata()"})

由此生成的HTML是这样的

<select id="Direction" name="Direction" onchange="getAlldata()">
<option>Home To School</option>
<option>School To Home</option>
</select>

但我想生成这样的 HTML

<select id="Direction" name="Direction" onchange="getAlldata()">
<option value="0">Home To School</option>
<option value="1">School To Home</option>
</select>

我怎样才能做到这一点。

4

2 回答 2

29

Use it like this

@Html.DropDownList("Direction", new SelectList(listItems , "Value" , "Text"),new {onchange = "getAlldata()"})
于 2013-04-19T07:29:31.033 回答
5

以下是一些如何DropDownList使用 Razor 构建的示例,例如 using SelectListItem

public ActionResult Index()
{
  var db = new NorthwindEntities();
  IEnumerable<SelectListItem> items = db.Categories
    .Select(c => new SelectListItem
                   {
                     Value = c.CategoryID.ToString(), 
                     Text = c.CategoryName
                   });
  ViewBag.CategoryID = items;
  return View();
}

编辑:

检查这个:

@Html.DropDownList("Direction", new List<SelectListItem>
{
  new SelectListItem{ Text = "Home To School", Value = "0" },
  new SelectListItem{ Text = "School To Home", Value = "1" } 
},new {onchange = "getAlldata()"})
于 2013-04-19T07:22:38.723 回答