Wednesday, June 25, 2014

MVC Razor - Enum Drop List


To Bind Enum value in Drop Down use the following

CSHTML

To display list of enum and select the value

@Html.EnumDropDownList(model => model.State, new { Id = "ddlState" })


To display list of enum item and keep binding when save/modify

@Html.EnumDropDownListFor(model => model.StateSelected, Model.State, new { Id = "ddlState" })

Note: model.StateSelected is int value.



Model

private int _StateSelected = 1;
public int StateSelected
{
  get { return _StateSelected; }
  set { _StateSelected = value; }
}


private State _State = 1;
public State State 
{
  get { return _State; }
  set { _Statevalue; }
}


Note: State is enum


public enum State
        {
            Tamilnadu =1,
            Karnadaka,
            ..
       
        }



Helper Class

  /// <summary>
        /// Enums the drop down list for.
        /// </summary>
        /// <typeparam name="TModel">The type of the model.</typeparam>
        /// <typeparam name="TEnum">The type of the enum.</typeparam>
        /// <param name="htmlHelper">The HTML helper.</param>
        /// <param name="expression">The expression.</param>
        /// <param name="htmlAttributes">The HTML attributes.</param>
        /// <returns></returns>
        public static MvcHtmlString EnumDropDownList<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TEnum>> expression, object htmlAttributes = null)
        {

            ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);

            Type enumType = GetNonNullableModelType(metadata);
            Type baseEnumType = Enum.GetUnderlyingType(enumType);

            IEnumerable<SelectListItem> items = from value in enumType.GetFields(BindingFlags.Static | BindingFlags.GetField | BindingFlags.Public)
                                                select new SelectListItem()
                                                {
                                                    Text = GetEnumDisplayValue(value),
                                                    Value = Convert.ChangeType(value.GetValue(null), baseEnumType).ToString(),
                                                    Selected = (value.GetValue(null).Equals(metadata.Model))
                                                };


            return SelectExtensions.DropDownList(htmlHelper, "EnumDropDown", items, htmlAttributes);

        }

        /// <summary>
        /// Enums the drop down list for.
        /// </summary>
        /// <typeparam name="TModel">The type of the model.</typeparam>
        /// <typeparam name="TEnum">The type of the enum.</typeparam>
        /// <typeparam name="TProperty">The type of the property.</typeparam>
        /// <param name="htmlHelper">The HTML helper.</param>
        /// <param name="expression">The expression.</param>
        /// <param name="enumType">Type of the enum.</param>
        /// <param name="htmlAttributes">The HTML attributes.</param>
        /// <returns></returns>
        public static MvcHtmlString EnumDropDownListFor<TModel, TEnum, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TEnum>> expression, TProperty enumType, object htmlAttributes = null)
        {

            ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);

            Type baseEnumType = Enum.GetUnderlyingType(typeof(TProperty));

            IEnumerable<SelectListItem> items = from value in typeof(TProperty).GetFields(BindingFlags.Static | BindingFlags.GetField | BindingFlags.Public)
                                                select new SelectListItem()
                                                {
                                                    Text = GetEnumDisplayValue(value),
                                                    Value = Convert.ChangeType(value.GetValue(null), baseEnumType).ToString(),
                                                    Selected = (value.GetValue(null).Equals(metadata.Model))
                                                };

            return SelectExtensions.DropDownListFor(htmlHelper, expression, items, htmlAttributes);
        }

        /// Gets the enum display value.
        /// </summary>
        /// <param name="field">The field.</param>
        /// <returns></returns>
        private static string GetEnumDisplayValue(FieldInfo field)
        {
            string text;

            DescriptionAttribute[] attributes =
           (DescriptionAttribute[])field.GetCustomAttributes(
           typeof(DescriptionAttribute),
           false);

            if (attributes != null &&
                attributes.Length > 0)
            {
                text = attributes[0].Description;
            }
            else
            {
                text = field.Name;
            }
            return text;
        }


        /// <summary>
        /// Gets the type of the non nullable model.
        /// </summary>
        /// <param name="modelMetadata">The model metadata.</param>
        /// <returns></returns>
        private static Type GetNonNullableModelType(ModelMetadata modelMetadata)
        {
            Type realModelType = modelMetadata.ModelType;
            Type underlyingType = Nullable.GetUnderlyingType(realModelType);

            if (underlyingType != null)
            {
                realModelType = underlyingType;
            }

            return realModelType;
        }

Thursday, June 19, 2014

C# - Enum Fully Qualified Name with space and Display

In Enum we can not have fully qualified name with spaces. To achieve that we can add the description attribute as follows

     ....
    using System.ComponentModel;
   ....

    public enum Employee
    {
        [Description("Balajiprasad Ramesh")]
        BalajiprasadRamesh = 1,
      
        [Description("Combined Name")]
        CombinedName = 2

    }



To display Enum description we can use the following code

private static string GetEnumDescription(object 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();
        }

Tuesday, June 17, 2014

MVC Razor - Convert Enum to List of SelectListItem

To Bind Enum values into Dropdown of MVC Razor, we need to convert them into list of SelectListitem.

Following class helps to convert Enum to List Of SelectListItem

Class:

public static class EnumToSelectedListItem
    {

        public static List<SelectListItem> ToSelectedListItem<T>()
        {
            List<SelectListItem> dropdown = Enum.GetValues(typeof(T)).Cast<T>().
                Select(v => new SelectListItem { Selected = false, Text = v.ToString(), Value = Convert.ToInt32(v).ToString() }).ToList();
            return dropdown;
        }


    }

SelectListItem Class Datastructure  (This class available in MVC)

// Summary:
    //     Represents the selected item in an instance of the System.Web.Mvc.SelectList
    //     class.
    public class SelectListItem
    {
        // Summary:
        //     Initializes a new instance of the System.Web.Mvc.SelectListItem class.
        public SelectListItem();

        // Summary:
        //     Gets or sets a value that indicates whether this System.Web.Mvc.SelectListItem
        //     is selected.
        //
        // Returns:
        //     true if the item is selected; otherwise, false.
        public bool Selected { get; set; }
        //
        // Summary:
        //     Gets or sets the text of the selected item.
        //
        // Returns:
        //     The text.
        public string Text { get; set; }
        //
        // Summary:
        //     Gets or sets the value of the selected item.
        //
        // Returns:
        //     The value.
        public string Value { get; set; }
    }


Consume:

  public List<SelectListItem> PersonEnumList
        {
            get
            {
                return EnumToSelectedListItem.ToSelectedListItem<PersonEnum>();
            }
        }