2

所以我正在学习 MVC/Razor,我不知道这是如何工作的。

在创建方法中

ViewBag.GenreId = new SelectList(db.Genres, "GenreId", "Name");

我在页面上

@Html.DropDownList("GenreId", String.Empty);

这有效。我感到困惑的是 ViewBag 和对象的属性之间的区别

所以我可以将第一行更改为

ViewBag.x= new SelectList(db.Genres, "GenreId", "Name");

@Html.DropDownList("x", String.Empty);

但是当然它不会绑定回对象那么当我可能不希望列表名称与对象属性同名时,为字段设置下拉列表的正确方法是什么?

我想可以直接从 Request.Form 对象中获取值,但这种方式绕过了模型绑定的全部要点。

4

2 回答 2

5

下拉列表助手自动搜索带有传递的字符串的选择列表

  1. 你的模型
  2. 查看包
  3. 临时数据

If a selectlist is created, the helper will render a dropdown list with name and id attributes with the same name as the string passed

In the process, the helper assumes that the id and name will be the same as the string passed. Whatever string you pass will populate the name and id attributes of the rendered dropdownlist.

if you use

@Html.DropDownList("x", String.Empty);

the resulting dropdown list will have name="x" and id="x". Any action method you post to will receive a parameter called "x".

If, on the otherhand, you wanted to differentiate the name of the bound parameter and you selectlist, you could use an overload of DropDownList

Html.DropDownList("Genres", (IEnumerable<SelectListItem>) ViewBag.GenresList)
于 2013-03-30T01:58:43.090 回答
1

I thought viewbag is a dynamic object and in the context of the above question viewbag.x would serve the purpose. I tried setting the following at the controllers end.

        Album album = db.Albums.Find(id);
        ViewBag.x = new SelectList(db.Genres, "GenreId", "Name",album.GenreId);

and retrieving the values at the Views end with the following and I had no issues.

        @Html.DropDownList("x","Please Select a Value")
        @Html.ValidationMessageFor(model => model.GenreId)
于 2013-05-09T02:08:53.427 回答