A handy extension method for DropDownList in ASP.NET MVC

Scott Allen has recently published a post named "DropDownListFor with ASP.NET MVC" and there are some cool ideas in the post. It's highly recommended reading Scott's post before mine.

After reading the article, an idea came into my mind. When working with DropDownList in ASP.NET, sometimes there is a need to add a new entry on the top of the DropDownList, named something like "Select an item..." and this was always a concern for me that what is a best way to do this from design perspective.

Therefor I wrote an extension method for the IEnumerable<SelectListItem> class to add this functionality to the DropDownList items in ASP.NET MVC.

    /// <summary>
    /// Adds a new entry to the dropdown items which is selected by default.
    /// </summary>
    /// <param name="listItems">dropdown items </param>
    /// <param name="text">text of the new entry</param>
    /// <param name="val">value of the new entry</param>
    /// <returns></returns>
    public static IEnumerable<SelectListItem> AddDefaultItem(this IEnumerable<SelectListItem> listItems,
                                string text = "Select an item...", string val = "-1")
    {
        var defaultItem = Enumerable.Repeat(new SelectListItem
        {
            Value = val,
            Text = text,
        }, count: 1);

        return defaultItem.Concat(listItems);
    }

The extension method has written for the IEnumerable<SelectListItem> class and so you just need to call it when you need to add a new entry on the top of the DropDownList, and this functionality is available all over the project.

 

Published Saturday, March 23, 2013 10:25 AM by mlife
Filed under: ,

Comments

# re: A handy extension method for DropDownList in ASP.NET MVC

Sunday, March 24, 2013 3:56 PM by danielhead

Why not just use this with the optionLabel parameter?

msdn.microsoft.com/.../ee703670(v=vs.108).aspx

# re: A handy extension method for DropDownList in ASP.NET MVC

Sunday, March 24, 2013 4:19 PM by mlife

@danielhead

By using OptionLabel, you are not able to specify a value for the item and that is always empty.

Leave a Comment

(required) 
(required) 
(optional)
(required)