Pages

Banner 468 x 60px

 

Tuesday, 4 September 2012

MVC Dropdown List using Enumerator(enum)

  In this post I will explain how to create a drop down list with Enumerator using MVC Rozar view. Many ways we have to do that but I will explain one of the easiest ways. If you follow this way we easily set select index of dropdown in Edit page also.

The view is
 @{
    var EnumInterval = from EnumDropDown.Interval n in 
                               Enum.GetValues(typeof(EnumDropDown.Interval))
    select new SelectListItem
    {
        Value = n.ToString(),
        Text = EnumDropDown.GetEnumDescription(n),
    };
}
The Helper class is look like below

using System.Reflection;
using System.ComponentModel;
namespace EnumHtmlHelper.Helper
{
    public static class EnumDropDown
    {
        public static string GetEnumDescription<TEnum>(TEnum value)
        {
            FieldInfo fi = value.GetType().GetField(value.ToString());
            DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.
                   GetCustomAttributes(typeof(DescriptionAttribute), false);
            if ((attributes != null) && (attributes.Length > 0))
                return attributes[0].Description;
            else
                return value.ToString();
        }
        public enum Interval
        {
            [Description("Daily")]
            D = 1,
            [Description("Quick")]
            Q = 2,
            [Description("Weekly")]
            W = 3
        } 
    }    
}
The View source look like bellow
 <select id="Interval" name="Interval">
         <option value="D">Daily</option>
         <option value="Q">Quick</option>
         <option value="W">Weekly</option>
</select>

No comments:

Post a Comment