将HtmlAttributes添加到@html.dropdownlist

时间:2014-01-20 10:07:24

标签: c# asp.net-mvc

您好我正在尝试将html属性data-bind添加到我的dropDownList。

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

@Html.DropDownList("DeviceDictionaryId" ,String.Empty)

其中DeviceDictionaryId是通过ViewBag从控制器发送的,如下所示:

var Ids = db.Dictionaries
           .Select(s => new
           {
               DeviceDictionaryId = s.DeviceDictionaryId,
               Description = s.DeviceManufacturer + " " + s.DeviceName
           })
           .ToList();
        ViewBag.DeviceDictionaryId = new SelectList(Ids, "DeviceDictionaryId", "Description");

但我找不到解决方法如何正确添加Htmlattribute。

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

public static MvcHtmlString DropDownList(
string name,
IEnumerable<SelectListItem> selectList,
string optionLabel,
Object htmlAttributes

对我来说:

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

但是我应该把它作为IEnumerable<SelectListItem> 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.

1 个答案:

答案 0 :(得分:0)

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

1) 使用Jquery并添加如下所示的属性:

$("#DeviceDictionaryId").attr("data-bind", "value:DeviceId");

2) 或者只是传递null而不是IEnumerable,一切正常:

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