pass enum to html.radiobuttonfor MVC3

前端 未结 2 635
暖寄归人
暖寄归人 2020-11-28 04:31

I Have an Enum Called ActionStatus that has 2 possible values open=0 and closed = 1

public enum ActionStatus
{
    Open,
    Closed
}

I wan

2条回答
  •  無奈伤痛
    2020-11-28 05:14

    Just add labels for radiobuttons

        public static class HtmlExtensions
    {
        public static MvcHtmlString RadioButtonForEnum(
            this HtmlHelper htmlHelper,
            Expression> expression
        )
        {
            var metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
    
            var names = Enum.GetNames(metaData.ModelType);
            var sb = new StringBuilder();
            foreach (var name in names)
            {
    
                var description = name;
    
                var memInfo = metaData.ModelType.GetMember(name);
                if (memInfo != null)
                {
                    var attributes = memInfo[0].GetCustomAttributes(typeof(DisplayAttribute), false);
                    if (attributes != null && attributes.Length > 0 )
                        description = ((DisplayAttribute)attributes[0]).Name;
                }
                var id = string.Format(
                    "{0}_{1}_{2}",
                    htmlHelper.ViewData.TemplateInfo.HtmlFieldPrefix,
                    metaData.PropertyName,
                    name
                );
    
                var radio = htmlHelper.RadioButtonFor(expression, name, new { id = id }).ToHtmlString();
                sb.AppendFormat(
                    " {2}",
                    id,
                    HttpUtility.HtmlEncode(description),
                    radio
                );
            }
            return MvcHtmlString.Create(sb.ToString());
        }
    }
    

    and the Model:

        public enum MeetingActionStatus                   
    {
    
        [Display(Name = "Open meeting")]
        Open,
    
        [Display(Name = "Closed meeting")]
        Closed             
    }          
    

提交回复
热议问题