Altaf Khatri
Assign css class to MVC dropdownlist - Html.Dropdownlist helper.
Either way is fine to use with the css class assignment below:
Method 1:
Method 2:
The code is as follows for the example described above, use it in the View of
the page.
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;
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");
using (TaskManagerEntities tme = new TaskManagerEntities())
{
iltblSecretQuestions = tme.udp_GetSecretQuestionlist().ToList();
}
ViewData["ddlList"] = new SelectList(iltblSecretQuestions, "pkSecretQuestion", "SecretQuestionDetail", "2");
<%=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: - The dropdownlist is casted to (IEnumerable<System.Web.Mvc.SelectListItem>) before it can be used.
- Check how the property name - value is associated. Name of the property is not enclosed in double quotes whereas the property value is.
