MVC3 Razor DropDownListFor枚举

试图让我的项目更新到MVC3,我无法find:

我有一个简单的数据types的ENUMS:

public enum States() { AL,AK,AZ,...WY } 

我想在一个包含这个数据types的模型视图中用作DropDown / SelectList:

 public class FormModel() { public States State {get; set;} } 

非常简单:当我为这个部分类使用自动生成视图时,它忽略了这种types。

我需要一个简单的select列表,当我点击提交和通过我的AJAX – JSON POST方法处理时,将enum的值设置为选定的项目。

而比视图(???!):

  <div class="editor-field"> @Html.DropDownListFor(model => model.State, model => model.States) </div> 

在此先感谢您的build议!

我为自己的项目做了一个。 下面的代码是我的帮手类的一部分,我希望我得到所有需要的方法。 写一个评论,如果它不工作,我会再次检查。

 public static class SelectExtensions { public static string GetInputName<TModel, TProperty>(Expression<Func<TModel, TProperty>> expression) { if (expression.Body.NodeType == ExpressionType.Call) { MethodCallExpression methodCallExpression = (MethodCallExpression)expression.Body; string name = GetInputName(methodCallExpression); return name.Substring(expression.Parameters[0].Name.Length + 1); } return expression.Body.ToString().Substring(expression.Parameters[0].Name.Length + 1); } private static string GetInputName(MethodCallExpression expression) { // p => p.Foo.Bar().Baz.ToString() => p.Foo OR throw... MethodCallExpression methodCallExpression = expression.Object as MethodCallExpression; if (methodCallExpression != null) { return GetInputName(methodCallExpression); } return expression.Object.ToString(); } public static MvcHtmlString EnumDropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression) where TModel : class { string inputName = GetInputName(expression); var value = htmlHelper.ViewData.Model == null ? default(TProperty) : expression.Compile()(htmlHelper.ViewData.Model); return htmlHelper.DropDownList(inputName, ToSelectList(typeof(TProperty), value.ToString())); } public static SelectList ToSelectList(Type enumType, string selectedItem) { List<SelectListItem> items = new List<SelectListItem>(); foreach (var item in Enum.GetValues(enumType)) { FieldInfo fi = enumType.GetField(item.ToString()); var attribute = fi.GetCustomAttributes(typeof(DescriptionAttribute), true).FirstOrDefault(); var title = attribute == null ? item.ToString() : ((DescriptionAttribute)attribute).Description; var listItem = new SelectListItem { Value = ((int)item).ToString(), Text = title, Selected = selectedItem == ((int)item).ToString() }; items.Add(listItem); } return new SelectList(items, "Value", "Text", selectedItem); } } 

使用它作为:

 Html.EnumDropDownListFor(m => m.YourEnum); 

更新

我已经创build了替代的Html Helpers。 所有你需要做的就是在views\web.config改变你的基本views\web.config

与他们在一起,你可以做到:

 @Html2.DropDownFor(m => m.YourEnum); @Html2.CheckboxesFor(m => m.YourEnum); @Html2.RadioButtonsFor(m => m.YourEnum); 

更多信息在这里: http : //blog.gauffin.org/2011/10/first-draft-of-my-alternative-html-helpers/

我在这里find了一个更简单的解决scheme: http : //coding-in.net/asp-net-mvc-3-method-extension/

 using System; using System.Linq.Expressions; using System.Web; using System.Web.Mvc; using System.Web.Mvc.Html; namespace EnumHtmlHelper.Helper { public static class EnumDropDownList { public static HtmlString EnumDropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> modelExpression, string firstElement) { var typeOfProperty = modelExpression.ReturnType; if(!typeOfProperty.IsEnum) throw new ArgumentException(string.Format("Type {0} is not an enum", typeOfProperty)); var enumValues = new SelectList(Enum.GetValues(typeOfProperty)); return htmlHelper.DropDownListFor(modelExpression, enumValues, firstElement); } } } 

剃刀的一条线就可以做到这一点:

 @Html.DropDownListFor(model => model.State, new SelectList(Enum.GetValues(typeof(MyNamespace.Enums.States)))) 

您也可以在链接的文章中find使用扩展方法的代码。

从ASP.NET MVC 5.1(RC1)开始 , EnumDropDownListFor作为HtmlHelper的扩展方法默认包含在内。

如果你想要一些非常简单的东西,那么还有另一种方法,这取决于你如何在数据库中存储状态。

如果你有这样的实体:

 public class Address { //other address fields //this is what the state gets stored as in the db public byte StateCode { get; set; } //this maps our db field to an enum public States State { get { return (States)StateCode; } set { StateCode = (byte)value; } } } 

然后生成下拉菜单就像这样简单:

 @Html.DropDownListFor(x => x.StateCode, from State state in Enum.GetValues(typeof(States)) select new SelectListItem() { Text = state.ToString(), Value = ((int)state).ToString() } ); 

LINQ不漂亮吗?

我能够在一个class轮中做到这一点。

 @Html.DropDownListFor(m=>m.YourModelProperty,new SelectList(Enum.GetValues(typeof(YourEnumType)))) 

根据@jgauffin接受的答案,我创build了自己的EnumDropDownListFor版本,它处理select项目的问题。

这个问题在另一个SO回答中详细介绍,基本上是误解DropDownList的不同重载行为。

我的完整代码(其中包括htmlAttributes重载等)是:

 public static class EnumDropDownListForHelper { public static MvcHtmlString EnumDropDownListFor<TModel, TProperty>( this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression ) where TModel : class { return EnumDropDownListFor<TModel, TProperty>( htmlHelper, expression, null, null); } public static MvcHtmlString EnumDropDownListFor<TModel, TProperty>( this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes ) where TModel : class { return EnumDropDownListFor<TModel, TProperty>( htmlHelper, expression, null, htmlAttributes); } public static MvcHtmlString EnumDropDownListFor<TModel, TProperty>( this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IDictionary<string, object> htmlAttributes ) where TModel : class { return EnumDropDownListFor<TModel, TProperty>( htmlHelper, expression, null, htmlAttributes); } public static MvcHtmlString EnumDropDownListFor<TModel, TProperty>( this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, string optionLabel ) where TModel : class { return EnumDropDownListFor<TModel, TProperty>( htmlHelper, expression, optionLabel, null); } public static MvcHtmlString EnumDropDownListFor<TModel, TProperty>( this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, string optionLabel, IDictionary<string,object> htmlAttributes ) where TModel : class { string inputName = GetInputName(expression); return htmlHelper.DropDownList( inputName, ToSelectList(typeof(TProperty)), optionLabel, htmlAttributes); } public static MvcHtmlString EnumDropDownListFor<TModel, TProperty>( this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, string optionLabel, object htmlAttributes ) where TModel : class { string inputName = GetInputName(expression); return htmlHelper.DropDownList( inputName, ToSelectList(typeof(TProperty)), optionLabel, htmlAttributes); } private static string GetInputName<TModel, TProperty>( Expression<Func<TModel, TProperty>> expression) { if (expression.Body.NodeType == ExpressionType.Call) { MethodCallExpression methodCallExpression = (MethodCallExpression)expression.Body; string name = GetInputName(methodCallExpression); return name.Substring(expression.Parameters[0].Name.Length + 1); } return expression.Body.ToString() .Substring(expression.Parameters[0].Name.Length + 1); } private static string GetInputName(MethodCallExpression expression) { // p => p.Foo.Bar().Baz.ToString() => p.Foo OR throw... MethodCallExpression methodCallExpression = expression.Object as MethodCallExpression; if (methodCallExpression != null) { return GetInputName(methodCallExpression); } return expression.Object.ToString(); } private static SelectList ToSelectList(Type enumType) { List<SelectListItem> items = new List<SelectListItem>(); foreach (var item in Enum.GetValues(enumType)) { FieldInfo fi = enumType.GetField(item.ToString()); var attribute = fi.GetCustomAttributes( typeof(DescriptionAttribute), true) .FirstOrDefault(); var title = attribute == null ? item.ToString() : ((DescriptionAttribute)attribute).Description; var listItem = new SelectListItem { Value = item.ToString(), Text = title, }; items.Add(listItem); } return new SelectList(items, "Value", "Text"); } } 

我在这里写了这个博客 。

这将有助于从枚举中select一个int值:这里SpecType是一个int字段,而enmSpecType是一个enum

 @Html.DropDownList( "SpecType", YourNameSpace.SelectExtensions.ToSelectList(typeof(NREticaret.Core.Enums.enmSpecType), Model.SpecType.ToString()), "Tip Seçiniz", new { gtbfieldid = "33", @class = "small" }) 

我对SelectList方法进行了如下修改,使其对我来说更好一些。 也许这对别人有用。

 public static SelectList ToSelectList<T>(T selectedItem) { if (!typeof(T).IsEnum) throw new InvalidEnumArgumentException("The specified type is not an enum"); var selectedItemName = Enum.GetName(typeof (T), selectedItem); var items = new List<SelectListItem>(); foreach (var item in Enum.GetValues(typeof(T))) { var fi = typeof(T).GetField(item.ToString()); var attribute = fi.GetCustomAttributes(typeof(DescriptionAttribute), true).FirstOrDefault(); var enumName = Enum.GetName(typeof (T), item); var title = attribute == null ? enumName : ((DescriptionAttribute)attribute).Description; var listItem = new SelectListItem { Value = enumName, Text = title, Selected = selectedItemName == enumName }; items.Add(listItem); } return new SelectList(items, "Value", "Text"); } 
  public enum EnumStates { AL = 0, AK = 1, AZ = 2, WY = 3 } @Html.DropDownListFor(model => model.State, (from EnumStates e in Enum.GetValues(typeof(EnumStates)) select new SelectListItem { Value = ((int)e).ToString(), Text = e.ToString() }), "select", new { @style = "" }) @Html.ValidationMessageFor(model => model.State) //With select //Or @Html.DropDownListFor(model => model.State, (from EnumStates e in Enum.GetValues(typeof(EnumStates)) select new SelectListItem { Value = ((int)e).ToString(), Text = e.ToString() }), null, new { @style = "" }) @Html.ValidationMessageFor(model => model.State) //With out select 

和Mike的一样(埋在冗长的回答之间)

model.truckimagelocation是TruckImageLocation枚举types的类实例属性

 @Html.DropDownListFor(model=>model.truckimagelocation,Enum.GetNames(typeof(TruckImageLocation)).ToArray().Select(f=> new SelectListItem() {Text = f, Value = f, Selected = false})) 

你可以在你的模型中使用枚举

你的Enum

 public enum States() { AL,AK,AZ,...WY } 

做一个模型

 public class enumclass { public States statesprop {get; set;} } 

在视图中

 @Html.Dropdownlistfor(a=>a.statesprop) 

在MVC5最简单的答案是定义枚举:

 public enum ReorderLevels { zero = 0, five = 5, ten = 10, fifteen = 15, twenty = 20, twenty_five = 25, thirty = 30 } 

绑定在视图中:

  <div class="form-group"> <label>Reorder Level</label> @Html.EnumDropDownListFor(m => m.ReorderLevel, "Choose Me", new { @class = "form-control" }) </div> 

这是用于所有枚举的最通用的代码。

 public static class UtilitiesClass { public static SelectList GetEnumType(Type enumType) { var value = from e in Enum.GetNames(enumType) select new { ID = Convert.ToInt32(Enum.Parse(enumType, e, true)), Name = e }; return new SelectList(value, "ID", "Name"); } } 

行动方法

 ViewBag.Enum= UtilitiesClass.GetEnumType(typeof (YourEnumType)); 

View.cshtml

  @Html.DropDownList("Type", (IEnumerable<SelectListItem>)ViewBag.Enum, new { @class = "form-control"})