Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@Html.DropDownList width

Q: How to set width for @Html.DropDownList (and not in css)?

@Html.DropDownList("ListId", String.Empty, new {style="width: 250px;"})  @* no go!*@ 
like image 922
genxgeek Avatar asked Sep 30 '11 19:09

genxgeek


People also ask

How do you increase the width of a selection box in HTML?

Answer: Use the CSS :focus pseudo-class By default the size of the <select> element is depend on the size of the largest <option> text. However, sometimes it is useful to set a fixed width to the select box and increase its size back to the original size when the user tries to select some option (i.e. on focus).

How do I add a class to a DropDownList in HTML?

As you can see from its reference page, the HtmlHelper. DropDownList Method (String, String, IEnumerable<SelectListItem>, Object) expects an object that "contains custom attributes for the element. The attribute names and values are retrieved through reflection by examining the properties of the object".


1 Answers

The second argument of the DropDownList helper must be an IEnumerable<SelectListItem>. You are passing a string (an empty one to be more precise). So in order to use this helper you will have to respect its signature:

@Html.DropDownList(     "ListId",      Enumerable.Empty<SelectListItem>(),      new { style = "width: 250px;" } ) 

Obviously generating an empty dropdown list is of little use. You probably have a view model (you should by the way) that you want to use to bind to:

@Html.DropDownList(     "ListId",      Model.MyList,      new { style = "width: 250px;" } ) 

and of course because you have a view model you should prefer to use the DropDownListFor helper:

@Html.DropDownListFor(     x => x.ListId,      Model.MyList,      new { style = "width: 250px;" } ) 

and finally to avoid cluttering your HTML with styles you should use an external CSS:

@Html.DropDownListFor(     x => x.ListId,      Model.MyList,      new { @class = "mycombo" } ) 

where in your external CSS you would define the .mycombo rule:

.mycombo {     width: 250px; } 

Now you have what I consider a proper code.

like image 172
Darin Dimitrov Avatar answered Sep 28 '22 04:09

Darin Dimitrov