Get the App
SLTechnology News&Howtos  ›  Development  › 

How asp.net MVC4 enumerates to generate DropDownList

Shulou Source: shulou.com Published: 2022-06-03 05:43:08 10月28日 Update

This article mainly shows you "asp.net MVC4 how to enumerate to generate DropDownList", the content is easy to understand, clear, hope to help you solve your doubts, the following let the editor lead you to study and learn "how to enumerate asp.net MVC4 to generate DropDownList" this article.

In MVC development, we often use enumerated types, usually enumerated types are used in DropDownList, each conversion is not a good way. This function is achieved by extension.

The code is as follows:

Public static class ExSelectListItem

{

Public static List 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 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 ()

}

}

We extend the Enum method to automatically convert the application of List in the foreground of MVC.

Use at the front desk:

@ Html.DorpDownList ((List) TempData ["enumerated types"])

It will work.

Background code application:

TempData [enumerated types] = ((Enum) enumerated types. Default type) .ToSelectListItem ()

In the extension to the second method, we pass the enumeration type name to determine whether the state is selected.

TempData [enumerated types] = ((Enum) enumerated types. Default type) .ToSelectListItem (default type)

The above is all the contents of the article "how asp.net MVC4 enumerates how to generate DropDownList". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Tags: Type generation content article code foreground method learning help application good function background easy to understand more organization status knowledge editing industry Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Redmi OPPO Reno Apple Microsoft vpn