65.9K
CodeProject is changing. Read more.
Home

Dropdown list extension method for HTML helper

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0 vote)

Jan 21, 2013

CPOL
viewsIcon

14655

How to create an extension mothod for a dropdown list in MVC.

Introduction

Here the information will describe that how to populate dropdown list. It describes about the basic steps for creating an extension method that populates dropdown list in MVC.

Background 

Suppose that we have the requirement to show some specific date format on our views that might be used somewhere else as well. In that case if we use this technique to create an extension method for this purpose and reuse, wherever required.

Using the code

Here the below code for the extension method is inside a separate file ExtensionMethods which is in the Solution MVCApp.

namespace MVCApp.ExtensionMethods
{  
    public static class DateFormat 
    { 
        public static MvcHtmlString GetDropDown(this HtmlHelper helper, string selectedID)
        {
            List<SelectListItem> list = new List<SelectListItem>();
            list.Add(new SelectListItem { Text = "dd/mm/yyyy", Value = "1", 
              Selected = (selectedID == "1" || string.IsNullOrEmpty(selectedID) || selectedID == "") ? true : false });
            list.Add(new SelectListItem { Text = "mm/dd/yyyy", Value = "2", 
              Selected = selectedID == "2" ? true : false });
            return helper.DropDownList("SelectedDateFormat", list);
        }
    } 
}

The page where we will use this extension method ,we need to import the namespace for the extension method-in my case it is like-

<%@ Import Namespace="MVCApp.ExtensionMethods" %>

Now here in the view page ,it can be used like:

<%:Html.GetDropDown(Model.SelectedDateFormat) %>

Points of Interest

As a rule we need to change the name "SelectedDateFormat" according to the property name being used.