我试图使用Html.DropDownListFor绑定一个枚举控制器,但是不管我从视图页面中选择什么,AgeRange都会得到一个值'0‘。有人能帮我解决这个问题吗?
编辑:控制器代码就位。
枚举类:
public enum AgeRange
{
Unknown = -1,
[Description("< 3 days")]
AgeLessThan3Days = 1,
[Description("3-6 days")]
AgeBetween3And6 = 2,
[Description("6-9 days")]
AgeBetween6And9 = 3,
[Description("> 9 days")]
AgeGreaterThan9Days = 4
}查看:
@Html.DropDownListFor(
model => model.Filter.AgeRangeId,
@Html.GetEnumDescriptions(typeof(AgeRange)),
new { @class = "search-dropdown", name = "ageRangeId" }
)控制器:
public ActionResult Search(int? ageRangeId)
{
var filter = new CaseFilter { AgeRangeId = (AgeRange)(ageRangeId ?? 0) };
}发布于 2012-04-24 15:22:50
你很接近了..。
我建议跟随this guy的脚步
发布于 2012-04-24 15:23:58
你必须为你的selectlist编写一个扩展方法来工作。
我用这个
public static SelectList ToSelectList<TEnum>(this TEnum enumeration) where TEnum : struct
{
//You can not use a type constraints on special class Enum.
if (!typeof(TEnum).IsEnum)
throw new ArgumentException("TEnum must be of type System.Enum");
var source = Enum.GetValues(typeof(TEnum));
var items = new Dictionary<object, string>();
foreach (var value in source)
{
FieldInfo field = value.GetType().GetField(value.ToString());
DisplayAttribute attrs = (DisplayAttribute)field.GetCustomAttributes(typeof(DisplayAttribute), false).First();
items.Add(value, attrs.GetName());
}
return new SelectList(items, Constants.PropertyKey, Constants.PropertyValue, enumeration);
}https://stackoverflow.com/questions/10293048
复制相似问题