Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a css class to select using @Html.DropDownList()

I'm building my first MVC application after years of doing webforms, and for some reason I am not able to make this work:

@Html.DropDownList("PriorityID", String.Empty, new {@class="textbox"} ) 

Error message:

System.Web.Mvc.HtmlHelper<SPDR.Models.Bug>' does not contain a definition for DropDownList and the best extension method overload System.Web.Mvc.Html.SelectExtensions.DropDownList(System.Web.Mvc.HtmlHelper, string, System.Collections.Generic.IEnumerable<System.Web.Mvc.SelectListItem>, object) has some invalid arguments

Any help greatly appreciated!

like image 498
Lee Bailey Avatar asked Sep 09 '11 20:09

Lee Bailey


People also ask

How to create dropdown with Html and CSS?

HTML) Use any element to open the dropdown content, e.g. a <span>, or a <button> element. Use a container element (like <div>) to create the dropdown content and add whatever you want inside of it. Wrap a <div> element around the elements to position the dropdown content correctly with CSS.

How to make drop down list CSS?

Example Explained Use any element to open the dropdown menu, e.g. a <button>, <a> or <p> element. Use a container element (like <div>) to create the dropdown menu and add the dropdown links inside it. Wrap a <div> element around the button and the <div> to position the dropdown menu correctly with CSS.

What is HTML DropDownList?

DropDownList(String, String, IEnumerable<SelectListItem>, Object, Object) Returns an HTML drop-down list control that has the specified name, custom attributes defined by an attribute object, and default selection, and that contains the specified list items and default item.


1 Answers

Looking at the controller, and learing a bit more about how MVC actually works, I was able to make sense of this.

My view was one of the auto-generated ones, and contained this line of code:

@Html.DropDownList("PriorityID", string.Empty) 

To add html attributes, I needed to do something like this:

@Html.DropDownList("PriorityID", (IEnumerable<SelectListItem>)ViewBag.PriorityID, new { @class="dropdown" }) 

Thanks again to @Laurent for your help, I realise the question wasn't as clear as it could have been...

UPDATE:

A better way of doing this would be to use DropDownListFor where possible, that way you don't rely on a magic string for the name attribute

@Html.DropDownListFor(x => x.PriorityID, (IEnumerable<SelectListItem>)ViewBag.PriorityID, new { @class = "dropdown" }) 
like image 67
Lee Bailey Avatar answered Oct 21 '22 04:10

Lee Bailey