1

AgeRangeを使用して列挙型をバインドしようとしてHtml.DropDownListForいますが、[表示]ページから選択したものに関係なく、Controllerは値「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) };
}
4

2 に答える 2

1

選択リストを機能させるには、拡張メソッドを作成する必要があります。

私はこれを使います

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);
}
于 2012-04-24T07:23:57.827 に答える
1

あなたは近いです...

この男と一緒にフォローすることをお勧めします

于 2012-04-24T07:22:50.447 に答える