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.



Comments have been disabled for this content.