In MVC development, we often use enumeration types. Generally, DropDownList is used for enumeration types. Each conversion is not a good solution. This function is implemented through extensions.
Copy codeThe Code is as follows:
Public static class ExSelectListItem
{
Public static List <SelectListItem> ToSelectListItem (this Enum valueEnum)
{
Return (from int value in Enum. GetValues (valueEnum. GetType ())
Select new SelectListItem
{
Text = Enum. GetName (valueEnum. GetType (), value ),
Value = value. ToString ()
}). ToList ();
}
Public static List <SelectListItem> ToSelectListItem (this Enum valueEnum, string selectName)
{
Return (from int value in Enum. GetValues (valueEnum. GetType ())
Select new SelectListItem
{
Text = Enum. GetName (valueEnum. GetType (), value ),
Value = Enum. GetName (valueEnum. GetType (), value ),
Selected = Enum. GetName (valueEnum. GetType (), value) = selectName? True: false
}). ToList ();
}
}
By extending the Enum method, we can automatically convert the List <SelectListItem> application in the MVC foreground.
Foreground use:
@ Html. DorpDownList (List <SelectListItem>) TempData ["Enumeration type"])
Looks good.
Background code application:
TempData ["Enumeration type"] = (Enum) Enumeration type. Default type). ToSelectListItem ();
In the second method of extension, we pass the enumeration type name to determine whether the instance is selected or not.
TempData ["Enumeration type"] = (Enum) Enumeration type. Default type). ToSelectListItem ("default type ");