Click here to Skip to main content
Click here to Skip to main content

Tagged as

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.

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.

License

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

Share

About the Author

rakesh1503
Software Developer Ebix software
India India
No Biography provided

Comments and Discussions

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