Altaf Khatri
Altaf Khatri



RSS feed for http://www.AltafKhatri.com website. Twitter account of http://www.AltafKhatri.com website.
∗Recently Added - How to take care of Betta fighter fish and increase life span?  10/30/2013


Find me on web

 LinkedIn

 Facebook

 Twitter

Assign css class to MVC dropdownlist - Html.Dropdownlist helper.

I was once struck with a situation where I wanted to assign a css class to MVC Html.DropDownList but I couldn't find out how to do it.

I was using the SelectList to bind the dropdownlist and wanted to assign the css class to the dropdownlist. I finally figured out how to do this and now I feel it was so simple. I am sure if you have faced this situation then you will be irritated by now. Let me jump to the solution before you start cursing me.

In the controller of the MVC view, bind the dropdownlist with either of the two methods described in this article to bind dropdownlist.
Either way is fine to use with the css class assignment below:

Method 1:
IList<SelectListItem> iliSLI = new List<SelectListItem>();
SelectListItem sli = new SelectListItem();
sli.Text = "What is your Mother's maiden name?";
sli.Value = "1";
sli.Selected = true;
iliSLI.Add(sli);
ViewData["ddlList"] = iliSLI; 

Method 2:
IList<tbl_SecretQuestion> iltblSecretQuestions = null;
using (TaskManagerEntities tme = new TaskManagerEntities())
{
   iltblSecretQuestions = tme.udp_GetSecretQuestionlist().ToList();
}
ViewData["ddlList"] = new SelectList(iltblSecretQuestions, "pkSecretQuestion", "SecretQuestionDetail", "2");

The code is as follows for the example described above, use it in the View of the page.
 <%=Html.DropDownList("ddlList", (IEnumerable<System.Web.Mvc.SelectListItem>)ViewData["ddlList"], new { @class = "hello", className = "asdfasdf" ,anyproperty = "putsometext"})%>

The className is defined twice as an example, and its not necessary to assign class with @class and className seperately.

In the view of the page, we are using the following overloaded method to assign the css class:

HtmlHelper.DropDownList(name, selectList, htmlAttributes)

Few important caveats:

  1. The dropdownlist is casted to (IEnumerable<System.Web.Mvc.SelectListItem>) before it can be used.
  2. Check how the property name - value is associated. Name of the property is not enclosed in double quotes whereas the property value is.




SiteMap  |  Contact Me