asp.net-mvc 将枚举传递给 MVC3 的 html.radiobutton

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5621013/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 01:06:57  来源:igfitidea点击:

pass enum to html.radiobuttonfor MVC3

asp.net-mvcasp.net-mvc-3enums

提问by MrBliz

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

我有一个名为 ActionStatus 的枚举,它有 2 个可能的值 open=0 和 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.

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

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

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

回答by Darin Dimitrov

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 typefor 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" />
}

回答by Alkaloon

Just add labels for radiobuttons

只需为单选按钮添加标签

    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 description = name;

            var memInfo = metaData.ModelType.GetMember(name);
            if (memInfo != null)
            {
                var attributes = memInfo[0].GetCustomAttributes(typeof(DisplayAttribute), false);
                if (attributes != null && attributes.Length > 0 )
                    description = ((DisplayAttribute)attributes[0]).Name;
            }
            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(description),
                radio
            );
        }
        return MvcHtmlString.Create(sb.ToString());
    }
}

and the Model:

和模型:

    public enum MeetingActionStatus                   
{

    [Display(Name = "Open meeting")]
    Open,

    [Display(Name = "Closed meeting")]
    Closed             
}