MVC DropDownList奇怪的行为

时间:2015-03-26 10:07:03

标签: c# asp.net-mvc asp.net-mvc-4 html.dropdownlistfor

我正在尝试使用以下代码将下拉列表与ViewBag绑定:
C#

ViewBag.Type = new List<SelectListItem>() 
{ 
    new SelectListItem(){ Value="1", Text="a" },
    new SelectListItem(){ Value="2", Text="b" }, 
    new SelectListItem(){ Value="3", Text="c", Selected = true }
}

CSHTML

@Html.DropDownList("Type", ViewBag.Type as IEnumerable<SelectListItem>, "Select type")

也试过

@Html.DropDownListFor(m => m.Type, ViewBag.Type as IEnumerable<SelectListItem>, "Select type")

但在上述两种情况下,Type字段未被自动选中。

但是当我尝试

@Html.DropDownList("Type1", ViewBag.Type as IEnumerable<SelectListItem>, "Select type")

然后通过c(值= 3)

选择Type字段

在上面的例子中,我刚刚更改了名称(Type - &gt; Type1)及其工作!!任何的想法 ?为什么它不使用实际的字段名称?

2 个答案:

答案 0 :(得分:1)

这是因为DropDownList帮助程序检查是否有ViewBag.FieldName,然后它会自动绑定。

  1. 您可以在ViewBag.Type
  2. 中更改ViewBag.SomethingElse
  3. 使用SelectList

        ViewBag.Type = new SelectList()
              { 
                  new SelectListItem(){ Value="1", Text="a" },
                  new SelectListItem(){ Value="2", Text="b" }, 
                  new SelectListItem(){ Value="3", Text="c", Selected = true }
              }
    
    ///----in your view
    
     @Html.DropDownListFor(m => m.Type, ViewBag.Type as SelectList, "Select type")
    

答案 1 :(得分:0)

您正在创建与ViewBag的密钥名称相同的Dropdownlist。因此它会在运行时发生冲突。这就是ID Type1的Dropdownlist工作的原因。