Saturday, October 8, 2011

Recently I have started working on ASP.NET MVC. There I have a trouble with MVC DropDownList using enum and its localization.

After googling I found some solutions and here is the final solution that worked for me.



        public static string GetEnumDescription<T>(T value, bool getLocalized = true)
        {
            FieldInfo fi = value.GetType().GetField(value.ToString());

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

            if (attributes != null &&
                attributes.Length > 0)
            {
                if (getLocalized)
                {
                    string localstring = Resources.Resources.ResourceManager.GetString(attributes[0].Description);
                    if (!string.IsNullOrEmpty(localstring))
                        return localstring;
                }
                return attributes[0].Description;
            }
            else
                return value.ToString();
        }

        public static MvcHtmlString EnumDropDownList<T>(this HtmlHelper htmlHelper, string name, T enu, int selectedValue)
        {
            string[] names = Enum.GetNames(typeof(T));
            Array values = Enum.GetValues(typeof(T));
            IList<SelectListItem> items = new List<SelectListItem>();
            int i = 0;
            foreach (T collateralTypeSetting in Enum.GetValues(typeof(T)))
            {
                string Text = GetEnumDescription(collateralTypeSetting);
                int val = (int)values.GetValue(i);

                SelectListItem it = new SelectListItem();
                it.Text = Text;
                it.Value = val.ToString();
                if (selectedValue == val)
                    it.Selected = true;
                items.Add(it);
                i++;
            }
            items[1].Selected = true;
            return htmlHelper.DropDownList(
             name,
             items
             );

        }