【问题标题】:RadioButtons for Enum (Bootstrap formatting)枚举的 RadioButtons(引导格式)
【发布时间】:2018-05-25 21:31:41
【问题描述】:

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

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

【问题讨论】:

  • 创建HtmlHelper扩展方法
  • this answer为例
  • @StephenMuecke 如果您不喜欢这个答案,为什么要对这个问题投反对票?无论如何,真的很喜欢你的建议,并决定采用其中的很大一部分来改进我的答案。感谢您的建议!
  • 这个问题被否决了,因为它离题了。这只是一个给我代码的问题。它没有表现出任何努力,包括没有尝试等。很明显你想添加一个自我答案,但这确实意味着你可以提出离题的问题。
  • 如果您想添加规范问题/答案,请阅读this meta post,我创建的一对示例请参考herehere。另请注意,它们通常是社区 Wiki 答案。

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


【解决方案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)

【讨论】:

  • 没有强类型模型绑定。没有客户端验证。仅当属性名称与 enum 的名称完全相同时才有效。不会根据属性的值选择正确的单选按钮,并且在返回视图时会丢失选择的值。等等等等等等
  • @StephenMuecke 根据您的建议进行了多项改进,其中许多基于your answer
猜你喜欢
  • 2012-05-12
  • 2010-09-28
  • 1970-01-01
  • 2014-05-29
  • 1970-01-01
  • 2016-02-28
  • 1970-01-01
  • 2012-12-31
相关资源
最近更新 更多