Home Ask Login Register

Developers Planet

Your answer is one click away!

gmalenko February 2016

asp.net MVC, Bootstrap and CSS. Drop down list issue

I am trying to figure out why Chrome is not rendering my drop down list correctly.

Chrome Error

However, it renders correctly in IE

IE Error

This is the line of code that is displaying this list

@Html.DropDownListFor(model => model.CountryID, new SelectList(Model.CountryList, "Value", "Text"), new { @class = "form-control", size = "18px" })

I am using the default Boostrap.css files provided by starting a new project in Visual Studio 2013. Any idea how to get this to render correctly?


Hadee February 2016

You need to add htmlAttributes to set your class in your razor. So change your code to :

@Html.DropDownListFor(model => model.CountryID, new SelectList(Model.CountryList, "Value", "Text"), htmlAttributes:new { @class = "form-control", size = "18px" })

Stephen Muecke February 2016

You creating invalid html, and there is no guarantee how various browsers (or even versions of the same browser) will handle invalid html.

Your DropDownListFor() method is adding a size attribute which expects an integer value so size="18px" is invalid and it would need to be size="18". However the size attribute defines how many items to display in a multiple select, so since you do not want a multiple select, just remove the attribute. Your code should be

@Html.DropDownListFor(m => m.CountryID, new SelectList(Model.CountryList, "Value", "Text"), new { @class = "form-control" })

Side note: Your new SelectList(Model.CountryList, "Value", "Text") code suggest that CountryList is already IEnumerable<SelectListItem>. If that is the case, its pointless extra overhead to be creating a new SelectList from an existing SelectList so your code should be

@Html.DropDownListFor(m => m.CountryID, Model.CountryList, new { @class = "form-control" })

Post Status

Asked in February 2016
Viewed 1,794 times
Voted 14
Answered 2 times


Leave an answer

Quote of the day: live life