tags:

views:

82

answers:

1

Hi,

I want to add two default options to my dropdowns in asp.net MVC using the html helper class, they are "--Please Select--" and "--Other--".

I can add one static option using

<%= Html.DropDownList("ddlserviceGroup",
    (IEnumerable<SelectListItem>)ViewData["ServiceGroups"], "--Select Item--")%>

But i need to add two options and can't seem to figure it using the HTML helper class

+1  A: 

The existing helper doesn't allow this. I'd suggest adding the options in the controller or perhaps writing your own extension method.

 var serviceGroups = db.Groups
                       .Select( g => new SelectListItem
                                     {
                                          Text = g.Name,
                                          Value = g.ID
                                     })
                       .ToList();
// prepend to list
serviceGroups.Insert( 0, new SelectListItem
                         {
                             Text = "--Select Item --",
                             Value = string.Empty
                         } );
// add at end
serviceGroups.Add( new SelectListItem
                   {
                       Text = "-- Other -- ",
                       Value = ????
                   });

ViewData["ServiceGroups"] = serviceGroups;

In View

<%=
    Html.DropDownList("ddlserviceGroup",
                      (IEnumerable<SelectListItem>)ViewData["ServiceGroups"]
 %>
tvanfosson