asp.net-mvc 将属性分配给@Html.DropdownList
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16828666/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Assign Attribute to @Html.DropdownList
提问by Rahul RJ
I want to assign some ID attribute name to my Dropdown list which is using data from the ViewBag as,
我想为我的下拉列表分配一些 ID 属性名称,该列表使用 ViewBag 中的数据,
ViewBag.Group = new SelectList(group, "GroupId", "Name");
and in the View side I have used Razor syntax for showing the Dropdown as,
在视图方面,我使用 Razor 语法将下拉列表显示为,
@Html.DropDownList("Group", "New", new { id="testID" } )
But I am getting the error on this line. Can I just assign ID of This Razor syntax? I know that the ID is generated with the Name "Playlist" But I am having 2 different dropdowns using same ViewBag. Because of that I have to assign different "ID" attribute value for them. How can it be done?
但我在这条线上收到错误。我可以只分配这个 Razor 语法的 ID 吗?我知道 ID 是用名称“播放列表”生成的,但我有 2 个使用相同 ViewBag 的不同下拉列表。因此,我必须为它们分配不同的“ID”属性值。怎么做到呢?
回答by Saravanan
You should be using something like this
你应该使用这样的东西
@Html.DropDownList("Group",null,new{@id="testID"});
because the data for the DropDownList comes from the ViewBag to name Group
因为 DropDownList 的数据来自 ViewBag 来命名 Group
回答by Aleksey Radzhabov
Try it:
尝试一下:
In controller
在控制器中
ViewBag.EmployeeId = new SelectList(db.tb_employees, "id", "last_name");
In View
在视图中
@Html.DropDownList("EmployeeId", (IEnumerable<SelectListItem>)ViewBag.EmployeeId,"Show All", new { @class = "form-control" })

