通过枚举html.radiobuttonfor MVC3 [英] pass enum to html.radiobuttonfor MVC3

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

问题描述

我有一个枚举调用ActionStatus具有开放2可能值= 0和闭合= 1

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

我要建立在我的编辑单选按钮组,并创建一个使用枚举来填充单选按钮用)在创建视图的默认值的意见和b)在编辑视图中当前选定的选项。

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

编辑:后低于这个Darins的回答是我的模型类

 命名空间Actioner.Models
{
[MetadataType(typeof运算(MeetingActionValidation))]
公共类MeetingAction
{
    [键]
    公众诠释MeetingActionId {搞定;组; }    [需要]
    [显示(名称=说明)]
    公共字符串描述{搞定;组; }    [需要]
    [显示(NAME =评审日期)]
    公众的DateTime REVIEWDATE {获取;设置; }    公众诠释状态{搞定;组; }    [ScaffoldColumn(假)]
    公众诠释MeetingId {搞定;组; }
    //公共虚拟会议会议{搞定;组; }    //公共虚拟的ICollection<使用者>用户{搞定;组; }
    公共虚拟的ICollection< ActionUpdate> ActionUpdates {搞定;组; }    公共MeetingActionStatus ActionStatus {搞定;组; }}公共枚举MeetingActionStatus
{
    打开,
    关闭
}

这是我的看法。

  @model Actioner.Models.MeetingAction
@using Actioner.Helpers
< D​​IV CLASS =编辑标记>
@ Html.LabelFor(型号=> model.Description)
< / DIV>
< D​​IV CLASS =主编场>
@ Html.EditorFor(型号=> model.Description)
@ Html.ValidationMessageFor(型号=> model.Description)
< / DIV>< D​​IV CLASS =编辑标记>
@ Html.LabelFor(型号=> model.ReviewDate)
< / DIV>
 < D​​IV CLASS =主编场>
@ Html.EditorFor(型号=> model.ReviewDate)
@ Html.ValidationMessageFor(型号=> model.ReviewDate)
< / DIV>< D​​IV CLASS =编辑标记>
@ Html.LabelFor(型号=> model.Status)
< / DIV>
< D​​IV CLASS =主编场> @ Html.RadioButtonForEnum(X => x.ActionStatus)< / DIV>

这是我创建控制器动作

 公共虚拟的ActionResult创建(INT ID)
    {        VAR meetingAction =新MeetingAction
        {
            MeetingId = ID,
            REVIEWDATE = DateTime.Now.AddDays(7)
        };        ViewBag.Title =创建行动;        返回查看(meetingAction);
    }

枚举在视图中显示正常,但当前选定的选项未保存到数据库


解决方案

 使用系统;
使用System.Collections.Generic;
使用System.Linq的;
使用System.Linq.Ex pressions;
使用System.Text;
使用的System.Web;
使用System.Web.Mvc;
使用System.Web.Mvc.Html;命名空间YourNamespace
{
    公共静态类HtmlExtensions
    {
        公共静态MvcHtmlString RadioButtonForEnum<的TModel,TProperty>(
            这与的HtmlHelper LT;的TModel>的HtmlHelper,
            防爆pression<&Func键LT;的TModel,TProperty>>前pression
        )
        {
            VAR元= ModelMetadata.FromLambdaEx pression(如pression,htmlHelper.ViewData);
            变种名称= Enum.GetNames(metaData.ModelType);
            VAR SB =新的StringBuilder();
            的foreach(在名称变量名称)
            {
                VAR ID =的String.Format(
                    {0} _ {1} _ {2},
                    htmlHelper.ViewData.TemplateInfo.HtmlField preFIX,
                    metaData.PropertyName,
                    名称
                );                VAR无线电= htmlHelper.RadioButtonFor(如pression,名称,新的{ID = ID})ToHtmlString()。
                sb.AppendFormat(
                    <标签= \\{0} \\> {1}< /标签> {2},
                    ID,
                    HttpUtility.HtmlEn code(名称),
                    无线电
                );
            }
            返回MvcHtmlString.Create(sb.ToString());
        }
    }
}

您也可以强制执行<一个href=\"http://msmvps.com/blogs/jon_skeet/archive/2009/09/10/generic-constraints-for-enums-and-delegates.aspx\">generic约束enum类型这个helper方法。

和则:

型号:

 公开枚举ActionStatus
{
    打开,
    关闭
}公共类MyViewModel
{
    公共ActionStatus状态{搞定;组; }
}

控制器:

 公共类HomeController的:控制器
{
    公众的ActionResult指数()
    {
        返回查看(新MyViewModel
        {
            状态= ActionStatus.Closed
        });
    }    [HttpPost]
    公众的ActionResult指数(MyViewModel模型)
    {
        返回查看(模型);
    }
}

查看:

  @model MyViewModel
@using(Html.BeginForm())
{
    @ Html.RadioButtonForEnum(X =&GT; x.Status)
    &LT;输入类型=提交VALUE =OK/&GT;
}

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

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

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