'태그를 입력해 주세요.'에 해당되는 글 1건

  1. 2013.03.18 [asp.net] enum 타입을 Generic 형식으로 <select /> 생성하기
2013. 3. 18. 10:01

아래와 같이 하면 Enum으로 데이터를 선언하고 실제 소스에서는 enum 형식으로 비교하고 UI에서는 Description 내용으로 보여줄 수 있다.


    public enum eGameInfo

    {

        [Description("사과")]

        Apple = 1,

        [Description("오렌지")]

        Orange = 2,

        [Description("망고")]

        Mango = 3,

    }


    public class HtmlHelper

    {

        public static string GetComboBoxHtml<TEnum>(string id, string style, TEnum eValue, bool isAll, string allText, string allValue, string[] exceptValues)

        {

            string html = "";


            string[] names = Enum.GetNames(typeof(TEnum));

            Array values = Enum.GetValues(typeof(TEnum));


            html += string.Format("<select id=\"{0}\">", id);

            for (int i = 0; i <= names.Length - 1; i++)

            {

                string value = Convert.ToInt32(values.GetValue(i)).ToString();

                string text = names[i];

                string name = HtmlHelper.GetDescriptName<TEnum>(text);

                if (!string.IsNullOrEmpty(name)) text = name;


                if (exceptValues.Where(code => code.Equals(value)).Count() == 0)

                {                    

                    html += string.Format("    <option value=\"{0}\" {2}>{1}</option>", value, text, eValue.ToString().Equals(values.GetValue(i).ToString()) ? "selected=\"selected\"" : "");

                }

            }

            html += string.Format("</select>");


            return html;

        }


        public static string GetDescriptName<T>(string memberName)

        {

            string name = string.Empty;

            var type = typeof(T);


            foreach (System.Reflection.MemberInfo member in type.GetMember(memberName))

            {

                object[] attributes = member.GetCustomAttributes(false);


                if (attributes.Length != 0)

                {

                    foreach (object attr in attributes)

                    {

                        DescriptionAttribute descAttr = attr as DescriptionAttribute;


                        if (descAttr != null)

                        {

                            name = descAttr.Description;

                            break;

                        }

                    }

                }

            }

            return name;

        }

    }

Posted by CoolDragon