繁体   English   中英

MVC DropDownList怪异的行为

[英]MVC DropDownList weird behaviour

我正在尝试使用以下代码将下拉列表与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")

然后Type字段被c选择(值= 3)

在上述情况下,我只是更改了名称(Type-> Type1)及其工作方式! 任何想法 ? 为什么它不能与实际的字段名称一起使用?

这是因为DropDownList助手会检查是否存在ViewBag.FieldName ,然后将其自动绑定。

  1. 你可以改变ViewBag.TypeViewBag.SomethingElse
  2. 使用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") 

您正在创建与ViewBag的键名相同的Dropdownlist,因此它将在运行时发生冲突。这就是ID类型为1的Dropdownlist起作用的原因。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM