Asp.net mvc 3 Html.dropdownlist用于始终返回值';0';不管选择什么

Asp.net mvc 3 Html.dropdownlist用于始终返回值';0';不管选择什么,asp.net-mvc-3,razor,drop-down-menu,html.dropdownlistfor,Asp.net Mvc 3,Razor,Drop Down Menu,Html.dropdownlistfor,我正在尝试使用Html.DropDownListFor绑定枚举AgeRange,但无论我从查看页面中选择什么,控制器都会得到一个值“0”。有人能帮我解决这个问题吗 编辑:控制器代码就位 枚举类: public enum AgeRange { Unknown = -1, [Description("< 3 days")] AgeLessThan3Days = 1, [Description("3-6 days")] AgeBetween3And6 = 2,

我正在尝试使用
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
}
控制器:

public ActionResult Search(int? ageRangeId)
{
   var filter = new CaseFilter { AgeRangeId = (AgeRange)(ageRangeId ?? 0) };
}
你很接近


我建议您在执行以下操作的同时

您必须为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);
}
publicstaticselectlist到SelectList(这个TEnum枚举),其中TEnum:struct
{
//不能对特殊类枚举使用类型约束。
if(!typeof(TEnum).IsEnum)
抛出新ArgumentException(“TEnum必须是System.Enum类型”);
var source=Enum.GetValues(typeof(TEnum));
var items=newdictionary();
foreach(源中的var值)
{
FieldInfo field=value.GetType().GetField(value.ToString());
DisplayAttribute attrs=(DisplayAttribute)字段。GetCustomAttributes(typeof(DisplayAttribute),false);
Add(value,attrs.GetName());
}
返回新的SelectList(项目、Constants.PropertyKey、Constants.PropertyValue、枚举);
}

我建议您需要一个右括号,所以我编辑了
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);
}