C# 将HtmlAttributes添加到@html.dropdownlist

C# 将HtmlAttributes添加到@html.dropdownlist,c#,asp.net-mvc,C#,Asp.net Mvc,您好,我正在尝试将html属性数据绑定到my dropDownList 在这里,您可以看到我的下拉代码: @Html.DropDownList("DeviceDictionaryId" ,String.Empty) 其中,控制器通过ViewBag发送DeviceDictionaryId,如下所示: var Ids = db.Dictionaries .Select(s => new { DeviceDictiona

您好,我正在尝试将html属性数据绑定到my dropDownList

在这里,您可以看到我的下拉代码:

@Html.DropDownList("DeviceDictionaryId" ,String.Empty)
其中,控制器通过ViewBag发送DeviceDictionaryId,如下所示:

var Ids = db.Dictionaries
           .Select(s => new
           {
               DeviceDictionaryId = s.DeviceDictionaryId,
               Description = s.DeviceManufacturer + " " + s.DeviceName
           })
           .ToList();
        ViewBag.DeviceDictionaryId = new SelectList(Ids, "DeviceDictionaryId", "Description");
$("#DeviceDictionaryId").attr("data-bind", "value:DeviceId");
但我无法找到正确添加Htmlattribute的解决方案

我知道我需要提供4个参数:

public static MvcHtmlString DropDownList(
string name,
IEnumerable<SelectListItem> selectList,
string optionLabel,
Object htmlAttributes
publicstaticmvchtmlstring下拉列表(
字符串名,
IEnumerable selectList,
字符串选项标签,
对象属性
)

对我来说:

名称:DeviceDictionaryId optionLabel=string.empty htmlattributes=new{data_bind=“value:Id”}

但是我应该把什么作为
IEnumerable selectList,

如果尝试将我的ViewBag.DeviceDictionaryId放在那里,则会出现以下错误:

 CS1973: 'System.Web.Mvc.HtmlHelper<dynamic>' has no applicable method named 'DropDownList' but appears to have an extension method by that name. Extension methods cannot be dynamically dispatched. Consider casting the dynamic arguments or calling the extension method without the extension method syntax.
CS1973:'System.Web.Mvc.HtmlHelper'没有名为'DropDownList'的适用方法,但似乎有一个同名的扩展方法。无法动态调度扩展方法。考虑在不使用扩展方法语法的情况下强制转换动态参数或调用扩展方法。

好的,我找到了两种绕过此错误的方法:

 CS1973: 'System.Web.Mvc.HtmlHelper<dynamic>' has no applicable method named 'DropDownList' but appears to have an extension method by that name. Extension methods cannot be dynamically dispatched. Consider casting the dynamic arguments or calling the extension method without the extension method syntax.
(一) 使用Jquery并添加如下属性:

var Ids = db.Dictionaries
           .Select(s => new
           {
               DeviceDictionaryId = s.DeviceDictionaryId,
               Description = s.DeviceManufacturer + " " + s.DeviceName
           })
           .ToList();
        ViewBag.DeviceDictionaryId = new SelectList(Ids, "DeviceDictionaryId", "Description");
$("#DeviceDictionaryId").attr("data-bind", "value:DeviceId");
(二) 或者只传递null而不是IEnumerable,一切都正常:

@Html.DropDownList("DeviceDictionaryId", null, new { data_bind = "value:DeviceId" }) 

它是一个
IEnumerable
,因此您应该将
id
变量放在那里(可能将泛型类型更改为
SelectListItem
)。
DeviceDictionaryId
的类型为
SelectList
,因此不起作用。第二个是最佳选择。这会更改可选选择列表的行为。默认情况下会选择第一个列表成员,而不是不带
htmlAttributes时的null。