Custom DropdownList HTML Helper in MVC3 Razor

  1. In MVC3 Razor we have HTML helpers to render different controls. 
  2. Instead of using these helpers we can create our own helper classes and methods and use them as we want.
  3. The creation of custom helpers provides flexibility to change the attributes and style of the control that renders.
  4. In this article we will create Custom HTML helper for DropdownList to render DropdownList i.e select element with options.


Following are the steps :

First we will create a folder named CustomHelpers. We will include a class file named CustomDropDownList.cs, which will hold code for Custom DropdownList control.

We have created the folder and the class file as mentioned earlier as shown in the above image.
The class file looks as below :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Text;
using System.Web.Routing;

namespace CustomHtmlHelpers.CustomHelpers
{
    public static class CustomDropdDownList
    {
        //This overload is extension method that accepts two parameters i.e. name and Ienumerable list of values to populate.
        public static MvcHtmlString Custom_DropdownList(this HtmlHelper helper ,string name, IEnumerable<SelectListItem> list)
        {
            //This method in turns calls below overload.
            return Custom_DropdownList(helper, name, list, null);
        }

        //This overload is extension method accepts name, list and htmlAttributes as parameters.
        public static MvcHtmlString Custom_DropdownList(this HtmlHelper helper, string name, IEnumerable<SelectListItem> list, object htmlAttributes)
        {
            //Creating a select element using TagBuilder class which will create a dropdown.
            TagBuilder dropdown = new TagBuilder("select");
            //Setting the name and id attribute with name parameter passed to this method.
            dropdown.Attributes.Add("name", name);
            dropdown.Attributes.Add("id", name);

            //Created StringBuilder object to store option data fetched oen by one from list.
            StringBuilder options = new StringBuilder();
            //Iterated over the IEnumerable list.
            foreach (var item in list)
            {
                //Each option represents a value in dropdown. For each element in the list, option element is created and appended to the stringBuilder object.
                options = options.Append("<option value='" + item.Value + "'>" + item.Text + "</option>");
            }
            //assigned all the options to the dropdown using innerHTML property.
            dropdown.InnerHtml = options.ToString();
            //Assigning the attributes passed as a htmlAttributes object.
            dropdown.MergeAttributes(new RouteValueDictionary(htmlAttributes));
            //Returning the entire select or dropdown control in HTMLString format.
            return MvcHtmlString.Create(dropdown.ToString(TagRenderMode.Normal));
        }
    }
}

In the above class we have created two overloads as per our convenience.

Overload 1 : The first overload accepts two parameters i.e. name and list. The name parameter is used to set name and id attribute. The list parameter is used to populate the dropdown. This method is extension method and accepts object of HtmlHelper class. The first parameter adds this overload to System.Web.MVC namespace. On view we can access this method using @html. This overload in turn calls another overload.


Overload 2 : The second overload accepts three parameters i.e. name, list and htmlAttributes object. The name parameter is used to set the name and id attribute. The list is used to populate the dropdown. The htmlAttributes object contains other attributes passed. 

       We have used TagBuilder class to create a select element which renders a dropdown. We are then iterating over the list and creating option element for each item in the list. We have appended the option elements in string format to object of StringBuilder class. This object is then added to the select element using innerHTML property. We have also assigned other attributes passed using htmlAttributes object.

View :



@model CustomHtmlHelpers.Models.Register

@{
    ViewBag.Title = "About Us";
    List<SelectListItem> list = new List<SelectListItem>();
    list.Add(new SelectListItem { Text = "Jack Wilshere", Value = "10" });
    list.Add(new SelectListItem { Text = "Thierry Henry", Value = "14" });
    list.Add(new SelectListItem { Text = "Cesc Fabregas", Value = "04" });
    list.Add(new SelectListItem { Text = "Santi Cazorla", Value = "19" });
    list.Add(new SelectListItem { Text = "Tomas Rosicky", Value = "08" });
}

<h2>About</h2>
<p>
@Html.Custom_DropdownList("Players", list)
@Html.Custom_DropdownList("Players", list, new { multiple = "multiple"})
</p>

UI :




Rendered HTML :

<select id="Players" name="Players"><option value='10'>Jack Wilshere</option><option value='14'>Thierry Henry</option><option value='04'>Cesc Fabregas</option><option value='19'>Santi Cazorla</option><option value='08'>Tomas Rosicky</option></select>
<select id="Players" multiple="multiple" name="Players"><option value='10'>Jack Wilshere</option><option value='14'>Thierry Henry</option><option value='04'>Cesc Fabregas</option><option value='19'>Santi Cazorla</option><option value='08'>Tomas Rosicky</option></select>


8 comments:

  1. Its Static data uploaded,Any idea for bring data from data base in c# MVC Razor??

    ReplyDelete
    Replies
    1. Hi. Thanks for leaving your comment.
      You can refer below link to get data from DB in MVC3 Razor.

      http://20fingers2brains.blogspot.in/2013/04/cascading-dropdowns-in-aspnet-mvc3.html

      :)

      Delete
  2. This comment has been removed by the author.

    ReplyDelete
  3. is your custom dropdownlist support validation??

    ReplyDelete
  4. i used this code , and i try to set id for this customdropdown via view like this
    @Html.CustomDropDownListFor(m => m.LocalTransfer.CustomerId, Model.LocalTransfer.CustomerList, "--Select--", new { @class = "form-control", style = "width: 100%;", @id = "CustomerId" })

    but id not set properly what can i do next ?
    please guide me

    ReplyDelete
  5. You forgot to add 'Selected'. Very useful though, thank you!

    ReplyDelete