将enum传递给html.Radio按钮,用于MVC 3?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (37)

我有一个名为ActionStatus的Enum,它有两个可能的值--open=0和Close=1

public enum ActionStatus
{
    Open,
    Closed
}

我希望在我的编辑和创建视图中生成单选按钮组,该视图使用枚举填充单选按钮,a)Create视图中的默认值,b)编辑视图中当前选择的选项。

我是否需要一个扩展方法,并且是否有人已经创建了一个扩展方法?

下面是我的模型类

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
}

这就是我的观点

@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>

这是我的创建控制器动作

public virtual ActionResult Create(int id)
    {

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

        ViewBag.Title = "Create Action"; 

        return View(meetingAction);
    } 

枚举在视图中显示得很好,但是当前选择的选项不会持久化到数据库中。

提问于
用户回答回答于
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());
        }
    }
}    

还可以强制执行枚举类型的泛型约束用于此助手方法。

模型:

public enum ActionStatus
{
    Open,
    Closed
}

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

控制器:

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

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

意见:

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

只需添加标签即可。

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

和模型:

    public enum MeetingActionStatus                   
{

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

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

扫码关注云+社区

领取腾讯云代金券