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

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

问题描述

基于 this 问题,我实现了 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 (enum) 以便选择单选按钮?

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());
    }
  }
}

添加对 web.config 的 <namespaces> 部分的引用

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

<add namespace="YourAssembly.Html "/>

并将其用作

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

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

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