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),
};
}
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
{
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
No comments:
Post a Comment