将枚举传递给 MVC3 的 html.radiobutton

发布于 2024-10-31 07:30:53 字数 2249 浏览 0 评论 0原文

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

public enum ActionStatus
{
    Open,
    Closed
}

我想在编辑中构建单选按钮组并创建使用枚举来填充单选按钮的视图 a) 创建视图中的默认值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);
    } 

枚举在视图中显示正常,但当前选择的选项不会保留到数据库中

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

撩动你心 2024-11-07 07:30:53
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" />
}
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" />
}
格子衫的從容 2024-11-07 07:30:53

只需添加单选按钮

    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             
}          

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             
}          
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文