首页 新闻 会员 周边

@Html.DropDownList 是如何绑定数据的?

0
悬赏园豆:10 [已解决问题] 解决于 2015-12-06 15:40

我在Controller中定义了一个action:

public ActionResult Edit(int id = 0)
{
        Album album = db.Albums.Find(id);
        if (album == null)
        {
              return HttpNotFound();
        }
        ViewBag.GenreId = new SelectList(db.Genres, "GenreId", "Name", album.GenreId);
            return View();
}

在视图中写了一个dropdownlist:

@Html.DropDownList("GenreId", "请选择")

在运行时发现dropdownlist中已经取出了所有的数据,但是看DropDownList的方法说明,它接收一个string类型的参数作为select的name属性,所以返回的html是

<select name="GenreId"> //这里的name和参数一致
  <option>请选择</option>
  <option value="1">数据一</option> //这是意料之外的结果
  <option value="2">数据二</option> //这是意料之外的结果
</select>

请问它是怎么把数据都取到的呢?后台只传了一个ViewBag.GenreId ,DropDownList是不是自动和ViewBag关联上了?

逐影的主页 逐影 | 小虾三级 | 园豆:982
提问于:2015-12-06 15:04
< >
分享
最佳答案
1

已经弄明白了,这是官方的说明:

The DropDownList helper used to create an HTML select list requires a IEnumerable , either explicitly or implicitly. That is, you can pass the IEnumerable explicitly to the DropDownList helper or you can add the IEnumerable to the ViewBag using the same name for the SelectListItem as the model property

可以传入明确的IEnumerable<SelectListItem>,也可以通过ViewBag或者ViewData隐式地传入,前提是需要相同的名称,比如:

ViewBag.GenreId或者ViewData["GenreId"]。官方示例:

public ActionResult SelectCategory() {

     List<SelectListItem> items = new List<SelectListItem>();

     items.Add(new SelectListItem { Text = "Action", Value = "0"});

     items.Add(new SelectListItem { Text = "Drama", Value = "1" });

     items.Add(new SelectListItem { Text = "Comedy", Value = "2", Selected = true });

     items.Add(new SelectListItem { Text = "Science Fiction", Value = "3" });

     ViewBag.MovieType = items;

     return View();

 }

视图:

@Html.DropDownList("MovieType")
逐影 | 小虾三级 |园豆:982 | 2015-12-06 15:39
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册