szpic
szpic

Reputation: 4496

Adding HtmlAttributes to @html.dropdownlist

Hello I'm trying to add html attribute data-bind to the my dropDownList.

Here You can see my code for dropdown:

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

where DeviceDictionaryId is send from controller via ViewBag like below:

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

but I can't find solution how to add Htmlattribute properly.

I Know that i need to provide 4 arguments:

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

)

For me:

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

but what should I put as IEnumerable<SelectListItem> selectList, ?

If try to put there my ViewBag.DeviceDictionaryId I get this error:

 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.

Upvotes: 1

Views: 7637

Answers (1)

szpic
szpic

Reputation: 4496

Ok I found two ways to bypass this error:

1) Use Jquery and add attributes like below:

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

2) Or just pass null instead of IEnumerable and everything works:

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

Upvotes: 1

Related Questions