枚举RadioButtonFor编辑模板设定值 [英] Enum RadioButtonFor Editor Template set value

查看:202
本文介绍了枚举RadioButtonFor编辑模板设定值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据这个问题,我实现了一个RadioButtonFor编辑模板。我的伟大工程,但目前不能传递你想要选择的值。

Based on this question, I implemented a RadioButtonFor Editor Template. I works great but currently you cannot pass the value you want selected.

EnumRadioButtonList.cshtml (Editor Template):
@model Enum

    @foreach (var value in Enum.GetValues(Model.GetType()))
    {
        if ((int)value > 0)
        { 
            @Html.RadioButtonFor(m => m, (int)value)  
            @Html.Label(value.ToString())
        }
    }

我把它从View:

I call it from View with:

@Html.EditorFor(m => m.QuestionResponse, "EnumRadioButtonList")

我如何通过这样的单选按钮被选中的值QuestionResponse(枚举)?

How do I pass the value QuestionResponse (enum) so that the radio button is selected?

推荐答案

您可以创建自定义的HTML帮助,这将给2路结合

You can create a custom html helper which will give 2-way binding

namespace YourAssembly.Html
{
  public static class EnumHelpers
  {
    public static MvcHtmlString EnumRadioButtonListFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression)
    {
      ModelMetadata metaData = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
      string name = ExpressionHelper.GetExpressionText(expression);
      if (!metaData.ModelType.IsEnum)
      {
        throw new ArgumentException(string.Format("The property {0} is not an enum", name));
      }
      string[] names = Enum.GetNames(metaData.ModelType);
      StringBuilder html = new StringBuilder();
      foreach(string value in names)
      {
        string id = string.Format("{0}_{1}", name, value);
        html.Append("<div>");
        html.Append(helper.RadioButtonFor(expression, value, new { id = id }));
        html.Append(helper.Label(id, value));
        html.Append("</div>");
      }
      return MvcHtmlString.Create(html.ToString());
    }
  }
}

添加到参考&LT;&命名空间GT; web.config中的部分

add a reference to the <namespaces> section of web.config

<add namespace="YourAssembly.Html "/>

和使用它作为

@Html.EnumRadioButtonListFor(m => m.QuestionResponse)

这篇关于枚举RadioButtonFor编辑模板设定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆