In one of my previous article I'm explained how to create a dropdownlist from a controller class. And in this post I'm going to explaine how to create a dropdownlist from an enum.
First create a helper ennum class with your dropdown items. Here I'm using three options "Daily","Quickly","Weekly".
Then add the following code into your (Razor) view to get the dropdown list.
The output of the above code look like this in page source
The output of the above code look like this in web page
Please share this post with your friends. If it's useful to you. Thanks!.
First create a helper ennum class with your dropdown items. Here I'm using three options "Daily","Quickly","Weekly".
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 } } }
Then add the following code into your (Razor) view to get the dropdown list.
<div class="ddlSmall">
@{ var EnumInterval = from Helper.EnumDropDown.Interval n in Enum.GetValues(typeof(Helper.EnumDropDown.Interval)) elect new SelectListItem { Value = n.ToString(), Text = EnumDropDown.GetEnumDescription(n), }; } </div>
The output of the above code look like this in page source
<select id="Interval" name="Interval"> <option value="D">Daily</option> <option value="Q">Quick</option> <option value="W">Weekly</option> </select>
0 comments:
Post a Comment
Share your thoughts here...