将枚举传递给 MVC3 的 html.radiobutton [英] pass enum to html.radiobuttonfor MVC3

查看:17
本文介绍了将枚举传递给 MVC3 的 html.radiobutton的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 ActionStatus 的枚举,它有 2 个可能的值 open=0 和 closed = 1

公共枚举 ActionStatus{打开,关闭}

我想在我的编辑中构建单选按钮组,并创建使用枚举填充单选按钮的视图:a) 创建视图中的默认值和 b) 编辑视图中当前选择的选项.

为此我需要一个扩展方法吗?有人已经创建了吗?

在下面达林斯的回答之后,这是我的模型类

命名空间 Actioner.Models{[元数据类型(typeof(MeetingActionValidation))]公开课 MeetingAction{[钥匙]公共 int MeetingActionId { 获取;放;}[必需的][显示(名称=描述")]公共字符串 描述 { 获取;放;}[必需的][显示(名称=审查日期")]公共日期时间审查日期{获取;设置;}公共 int 状态{获取;放;}[ScaffoldColumn(false)]公共 int MeetingId { 获取;放;}//公共虚拟会议 { get;放;}//公共虚拟ICollection<用户>用户{得到;放;}公共虚拟 ICollection动作更新 { 获取;放;}公共 MeetingActionStatus ActionStatus { 获取;放;}}公共枚举 MeetingActionStatus{打开,关闭}

这是我的看法

@model Actioner.Models.MeetingAction@using Actioner.Helpers<div class="editor-label">@Html.LabelFor(model => model.Description)

<div class="editor-field">@Html.EditorFor(model => model.Description)@Html.ValidationMessageFor(model => model.Description)

<div class="editor-label">@Html.LabelFor(model => model.ReviewDate)

<div class="editor-field">@Html.EditorFor(model =>model.ReviewDate)@Html.ValidationMessageFor(model =>model.ReviewDate)

<div class="editor-label">@Html.LabelFor(model => model.Status)

<div class="editor-field">@Html.RadioButtonForEnum(x => x.ActionStatus)

这是我的创建控制器动作

public virtual ActionResult Create(int id){var meetingAction = 新会议行动{会议 ID = id,ReviewDate = DateTime.Now.AddDays(7)};ViewBag.Title = "创建动作";返回视图(会议操作);}

枚举在视图中显示正常,但当前选择的选项没有持久化到数据库中

解决方案

using System;使用 System.Collections.Generic;使用 System.Linq;使用 System.Linq.Expressions;使用 System.Text;使用 System.Web;使用 System.Web.Mvc;使用 System.Web.Mvc.Html;命名空间 你的命名空间{公共静态类 HtmlExtensions{public static MvcHtmlString RadioButtonForEnum(这个 HtmlHelper<TModel>htmlHelper,表达式<Func<TModel,TProperty>表达){var metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);var names = Enum.GetNames(metaData.ModelType);var sb = new StringBuilder();foreach(名称中的变量名称){var id = string.Format("{0}_{1}_{2}",htmlHelper.ViewData.TemplateInfo.HtmlFieldPrefix,元数据.属性名称,名称);var radio = htmlHelper.RadioButtonFor(expression, name, new { id = id }).ToHtmlString();sb.AppendFormat("<label for="{0}">{1}</label> {2}",ID,HttpUtility.HtmlEncode(name),收音机);}返回 MvcHtmlString.Create(sb.ToString());}}}

您还可以强制执行 此辅助方法对枚举类型的通用约束.

然后:

型号:

公共枚举 ActionStatus{打开,关闭}公共类 MyViewModel{公共 ActionStatus 状态 { 获取;放;}}

控制器:

公共类 HomeController : 控制器{公共 ActionResult 索引(){返回视图(新的 MyViewModel{状态 = ActionStatus.Closed});}[HttpPost]公共 ActionResult 索引(MyViewModel 模型){返回视图(模型);}}

查看:

@model MyViewModel@using (Html.BeginForm()){@Html.RadioButtonForEnum(x => x.Status)<input type="submit" value="OK"/>}

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

public enum ActionStatus
{
    Open,
    Closed
}

I want to build radio button group in my edit and create views that uses the enum to populate the radio buttons with a) a default value in the create view and b) the currently selected option in the edit view.

Do i need an extension method for this, and has anybody already created one?

EDIT: After Darins's answer below this is my Model class

namespace Actioner.Models
{
[MetadataType(typeof(MeetingActionValidation))]
public class MeetingAction
{
    [Key]
    public int MeetingActionId              { get; set; }       

    [Required]
    [Display(Name = "Description")]
    public string Description  { get; set; }

    [Required]
    [Display(Name = "Review Date")]
    public DateTime ReviewDate       { get ;set; }

    public int Status{ get; set; }

    [ScaffoldColumn(false)]
    public int MeetingId             { get; set; }


    //public virtual Meeting Meeting { get; set; }

    //public virtual ICollection<User> Users { get; set; }
    public virtual ICollection<ActionUpdate> ActionUpdates { get; set; }

    public MeetingActionStatus ActionStatus { get; set; }

}

public enum MeetingActionStatus 
{
    Open,
    Closed
}

and this is my view

@model Actioner.Models.MeetingAction
@using Actioner.Helpers


<div class="editor-label">
@Html.LabelFor(model => model.Description)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Description)
@Html.ValidationMessageFor(model => model.Description)
</div>

<div class="editor-label">
@Html.LabelFor(model => model.ReviewDate)
</div>
 <div class="editor-field">
@Html.EditorFor(model => model.ReviewDate)
@Html.ValidationMessageFor(model => model.ReviewDate)
</div>

<div class="editor-label">
@Html.LabelFor(model => model.Status)
</div>
<div class="editor-field">

 @Html.RadioButtonForEnum(x => x.ActionStatus)

</div>

And this is my create controller action

public virtual ActionResult Create(int id)
    {

        var meetingAction = new MeetingAction
        {
            MeetingId = id,
            ReviewDate = DateTime.Now.AddDays(7)
        };

        ViewBag.Title = "Create Action"; 

        return View(meetingAction);
    } 

The enum displays fine in the view, but the currently selected option is not persisted to the database

解决方案

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;

namespace YourNamespace
{
    public static class HtmlExtensions
    {
        public static MvcHtmlString RadioButtonForEnum<TModel, TProperty>(
            this HtmlHelper<TModel> htmlHelper, 
            Expression<Func<TModel, TProperty>> expression
        )
        {
            var metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
            var names = Enum.GetNames(metaData.ModelType);
            var sb = new StringBuilder();
            foreach (var name in names)
            {
                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(
                    "<label for="{0}">{1}</label> {2}", 
                    id, 
                    HttpUtility.HtmlEncode(name), 
                    radio
                );
            }
            return MvcHtmlString.Create(sb.ToString());
        }
    }
}    

You could also enforce a generic constraint to an enum type for this helper method.

and then:

Model:

public enum ActionStatus
{
    Open,
    Closed
}

public class MyViewModel
{
    public ActionStatus Status { get; set; }
}

Controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View(new MyViewModel
        {
            Status = ActionStatus.Closed
        });
    }

    [HttpPost]
    public ActionResult Index(MyViewModel model)
    {
        return View(model);
    }
}

View:

@model MyViewModel
@using (Html.BeginForm())
{
    @Html.RadioButtonForEnum(x => x.Status)
    <input type="submit" value="OK" />
}

这篇关于将枚举传递给 MVC3 的 html.radiobutton的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆