尝试将我的项目更新为MVC3,这是我无法找到的:
我有一个简单的ENUMS数据类型:
public enum States()
{
AL,AK,AZ,...WY
}
我想在包含此数据类型的模型视图中将其用作DropDown / SelectList:
public class FormModel()
{
public States State {get; set;}
}
非常简单:当我为这个分部类使用自动生成视图时,它忽略了这种类型。
我需要一个简单的选择列表,当我通过我的AJAX - JSON POST方法点击提交和处理时,将枚举的值设置为所选项。
而不是视图(???!):
<div class="editor-field">
@Html.DropDownListFor(model => model.State, model => model.States)
</div>
提前感谢您的建议!
答案 0 :(得分:198)
我在这里找到了一种更简单的解决方案: 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))))
您还可以在链接文章中找到使用扩展方法执行此操作的代码。
答案 1 :(得分:55)
我刚刚为自己的项目制作了一个。下面的代码是我的助手类的一部分,我希望我得到了所有需要的方法。如果它不起作用,请写评论,我会再次检查。
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);
<强>更新强>
我已经创建了替代的Html助手。您只需在views\web.config
中更改baseviewpage。
有了他们,你可以这样做:
@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/
答案 2 :(得分:23)
自ASP.NET MVC 5.1 (RC1)起,EnumDropDownListFor
默认包含在HtmlHelper
的扩展方法中。
答案 3 :(得分:17)
如果您想要一些非常简单的东西,那么还有另一种方式,具体取决于您在数据库中存储状态的方式。
如果您有这样的实体:
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不漂亮吗?
答案 4 :(得分:12)
我能够在一个班轮里做到这一点。
@Html.DropDownListFor(m=>m.YourModelProperty,new SelectList(Enum.GetValues(typeof(YourEnumType))))
答案 5 :(得分:7)
根据@jgauffin接受的答案,我创建了自己的EnumDropDownListFor
版本,该版本处理选择项目的问题。
问题在another SO answer here:中有详细说明,基本上是由于对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");
}
}
我已经写了on my blog here。
答案 6 :(得分:3)
这有助于从枚举中选择一个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"
})
答案 7 :(得分:3)
我对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");
}
答案 8 :(得分:3)
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
答案 9 :(得分:2)
与迈克相同(埋在冗长的回复中)
model.truckimagelocation是TruckImageLocation枚举类型的类实例属性
@Html.DropDownListFor(model=>model.truckimagelocation,Enum.GetNames(typeof(TruckImageLocation)).ToArray().Select(f=> new SelectListItem() {Text = f, Value = f, Selected = false}))
答案 10 :(得分:1)
您可以在模型中使用枚举
你的枚举
public enum States()
{
AL,AK,AZ,...WY
}
制作模型
public class enumclass
{
public States statesprop {get; set;}
}
在视图中
@Html.Dropdownlistfor(a=>a.statesprop)
答案 11 :(得分:1)
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>
答案 12 :(得分:1)
这是最通用的代码,将用于所有枚举。
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"})