枚举的RadioButtons(引导格式)

时间:2017-12-12 08:53:53

标签: c# asp.net-mvc twitter-bootstrap razor

我的模型中有很多枚举,并且希望以自己的形式为它们生成单选按钮,而不是为每个值添加@Html.RadiobuttonFor。例如,我有以下枚举:

public enum Gender
{
    Male = 1,
    Female = 2
}

1 个答案:

答案 0 :(得分:1)

创建以下帮助程序类:

using System.Linq.Expressions;
using System.Text;

namespace System.Web.Mvc.Html
{
    public static class EnumHelpers
    {
        public static MvcHtmlString EnumRadioButtonListFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression, ListDirection listDirection)
        {
            ModelMetadata metaData = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
            string enumName = ExpressionHelper.GetExpressionText(expression);
            if (!metaData.ModelType.IsEnum)
                throw new ArgumentException(string.Format("The property {0} is not an enum", enumName));

            var html = new StringBuilder();

            string name = ExpressionHelper.GetExpressionText(expression);
            string[] names = Enum.GetNames(metaData.ModelType);
            foreach (string value in names)
            {
                string id = string.Format("{0}_{1}", name, value);
                html.Append(String.Format("<label class=\"{1}\" for=\"{0}\">",
                    new string[] {
                                    id,
                                    listDirection == ListDirection.Horizontal ? "radio-inline" : "radio"
                            }));
                html.Append(helper.RadioButtonFor(expression, value, new { id = id }));
                html.Append(String.Format(" {0}</label>", value));
            }

            return MvcHtmlString.Create(html.ToString());
        }

        public enum ListDirection
        {
            Vertical,
            Horizontal
        }
    }
}

然后在Razor视图中调用它:

@Html.EnumRadioButtonListFor(model => model.PaymentMethod, EnumHelpers.ListDirection.Horizontal)