12 people like it.

Enum -> MVC3 SelectList

Converts an Enum to a Selectlist which can be used by a @Html.DropDownList

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
open System
open System.Web
open System.Web.Mvc


let enumToSelectList<'a, 'b when 'a : enum<'b> and 'a : equality>(enum:'a) = 
  let toSelectListItem (valv, text, selected) =
    let sli = new SelectListItem()
    sli.Selected <- selected
    sli.Value <- valv
    sli.Text <- text
    sli

  System.Enum.GetValues(typeof<'a>) 
    |> Seq.cast<'a> 
    |> Seq.map (fun en -> toSelectListItem ((LanguagePrimitives.EnumToValue en).ToString(), en.ToString(), (enum = en)))
namespace System
namespace System.Web
val enumToSelectList : enum:'a -> seq<obj> (requires enum and equality)

Full name: Script.enumToSelectList
val enum : value:int32 -> 'U (requires enum)

Full name: Microsoft.FSharp.Core.Operators.enum
val enum : 'a (requires enum and equality)
val toSelectListItem : ('c * 'd * 'e -> 'f)
val valv : 'c
val text : 'd
val selected : 'e
val sli : 'f
namespace System.Text
type Enum =
  member CompareTo : target:obj -> int
  member Equals : obj:obj -> bool
  member GetHashCode : unit -> int
  member GetTypeCode : unit -> TypeCode
  member HasFlag : flag:Enum -> bool
  member ToString : unit -> string + 3 overloads
  static member Format : enumType:Type * value:obj * format:string -> string
  static member GetName : enumType:Type * value:obj -> string
  static member GetNames : enumType:Type -> string[]
  static member GetUnderlyingType : enumType:Type -> Type
  ...

Full name: System.Enum
Enum.GetValues(enumType: Type) : Array
val typeof<'T> : Type

Full name: Microsoft.FSharp.Core.Operators.typeof
module Seq

from Microsoft.FSharp.Collections
val cast : source:Collections.IEnumerable -> seq<'T>

Full name: Microsoft.FSharp.Collections.Seq.cast
val map : mapping:('T -> 'U) -> source:seq<'T> -> seq<'U>

Full name: Microsoft.FSharp.Collections.Seq.map
val en : 'a (requires enum and equality)
module LanguagePrimitives

from Microsoft.FSharp.Core
val EnumToValue : enum:'Enum -> 'T (requires enum)

Full name: Microsoft.FSharp.Core.LanguagePrimitives.EnumToValue
Object.ToString() : string
Next Version Raw view Test code New version

More information

Link:http://fssnip.net/9G
Posted:12 years ago
Author:christophd
Tags: mvc3 , mvc , enum