Click here to Skip to main content
12,942,930 members (57,253 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as


1 bookmarked
Posted 21 Jan 2013

Dropdown list extension method for HTML helper

, 21 Jan 2013 CPOL
Rate this:
Please Sign up or sign in to vote.
How to create an extension mothod for a dropdown list in MVC.


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.


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.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Software Developer HCL
India India
No Biography provided

You may also be interested in...

Comments and Discussions

-- There are no messages in this forum --
Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170518.1 | Last Updated 21 Jan 2013
Article Copyright 2013 by rakesh1503
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid