source

Enum을 ASP의 DropDownList 컨트롤에 바인드하려면 어떻게 해야 합니다.인터넷?

itover 2023. 4. 22. 09:22
반응형

Enum을 ASP의 DropDownList 컨트롤에 바인드하려면 어떻게 해야 합니다.인터넷?

다음과 같은 간단한 열거가 있다고 가정합니다.

enum Response
{
    Yes = 1,
    No = 2,
    Maybe = 3
}

이 열거형을 DropDownList 컨트롤에 바인드하여 설명을 목록에 표시하고 옵션이 선택되면 관련 수치(1, 2, 3)를 취득하려면 어떻게 해야 합니까?

데이터가 열거형이기 때문에 바인드하지 않고 컴파일 시간 이후에도 변경되지 않을 것입니다( 중 하나라도 구부정하게 있는 경우가 아니라면).

열거를 반복하는 것이 좋습니다.

Dim itemValues As Array = System.Enum.GetValues(GetType(Response))
Dim itemNames As Array = System.Enum.GetNames(GetType(Response))

For i As Integer = 0 To itemNames.Length - 1
    Dim item As New ListItem(itemNames(i), itemValues(i))
    dropdownlist.Items.Add(item)
Next

또는 C#에서도 마찬가지입니다.

Array itemValues = System.Enum.GetValues(typeof(Response));
Array itemNames = System.Enum.GetNames(typeof(Response));

for (int i = 0; i <= itemNames.Length - 1 ; i++) {
    ListItem item = new ListItem(itemNames[i], itemValues[i]);
    dropdownlist.Items.Add(item);
}

클래스를 합니다.EnumerationIDictionary<int,string>Enumeration에서 (Enum 값과 이름 쌍)을 선택한 후 IDictionary를 바인딩 가능한 Control에 바인드합니다.

public static class Enumeration
{
    public static IDictionary<int, string> GetAll<TEnum>() where TEnum: struct
    {
        var enumerationType = typeof (TEnum);

        if (!enumerationType.IsEnum)
            throw new ArgumentException("Enumeration type is expected.");

        var dictionary = new Dictionary<int, string>();

        foreach (int value in Enum.GetValues(enumerationType))
        {
            var name = Enum.GetName(enumerationType, value);
            dictionary.Add(value, name);
        }

        return dictionary;
    }
}

예:유틸리티 클래스를 사용하여 열거 데이터를 컨트롤에 바인딩

ddlResponse.DataSource = Enumeration.GetAll<Response>();
ddlResponse.DataTextField = "Value";
ddlResponse.DataValueField = "Key";
ddlResponse.DataBind();

ASP에 사용합니다.NET MVC:

Html.DropDownListFor(o => o.EnumProperty, Enum.GetValues(typeof(enumtype)).Cast<enumtype>().Select(x => new SelectListItem { Text = x.ToString(), Value = ((int)x).ToString() }))

내 버전은 위의 압축 형식일 뿐입니다.

foreach (Response r in Enum.GetValues(typeof(Response)))
{
    ListItem item = new ListItem(Enum.GetName(typeof(Response), r), r.ToString());
    DropDownList1.Items.Add(item);
}
public enum Color
{
    RED,
    GREEN,
    BLUE
}

모든 Enum 유형은 시스템에서 파생됩니다.Enum. 드롭다운 목록 컨트롤에 데이터를 바인딩하고 값을 검색하는 데 도움이 되는 두 가지 정적 메서드가 있습니다.Enum 입니다.GetNames 및 Enum.해석. GetNames를 사용하면 다음과 같이 드롭다운리스트 컨트롤에 바인드 할 수 있습니다.

protected System.Web.UI.WebControls.DropDownList ddColor;

private void Page_Load(object sender, System.EventArgs e)
{
     if(!IsPostBack)
     {
        ddColor.DataSource = Enum.GetNames(typeof(Color));
        ddColor.DataBind();
     }
}

Enum 값을 Back on Selection으로 되돌리는 경우...

  private void ddColor_SelectedIndexChanged(object sender, System.EventArgs e)
  {
    Color selectedColor = (Color)Enum.Parse(typeof(Color),ddColor.SelectedValue
  }

모든 투고를 읽은 후 드롭다운목록에 열거형 설명을 표시하고 Edit 모드로 표시할 때 드롭다운에서 Model에서 적절한 값을 선택할 수 있도록 지원하는 포괄적인 솔루션이 떠올랐습니다.

열거:

using System.ComponentModel;
public enum CompanyType
{
    [Description("")]
    Null = 1,

    [Description("Supplier")]
    Supplier = 2,

    [Description("Customer")]
    Customer = 3
}

열거 확장 클래스:

using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web.Mvc;

public static class EnumExtension
{
    public static string ToDescription(this System.Enum value)
    {
        var attributes = (DescriptionAttribute[])value.GetType().GetField(value.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), false);
        return attributes.Length > 0 ? attributes[0].Description : value.ToString();
    }

    public static IEnumerable<SelectListItem> ToSelectList<T>(this System.Enum enumValue)
    {
        return
            System.Enum.GetValues(enumValue.GetType()).Cast<T>()
                  .Select(
                      x =>
                      new SelectListItem
                          {
                              Text = ((System.Enum)(object) x).ToDescription(),
                              Value = x.ToString(),
                              Selected = (enumValue.Equals(x))
                          });
    }
}

모델 클래스:

public class Company
{
    public string CompanyName { get; set; }
    public CompanyType Type { get; set; }
}

및 표시:

@Html.DropDownListFor(m => m.Type,
@Model.Type.ToSelectList<CompanyType>())

모델에 바인딩하지 않고 드롭다운을 사용하는 경우 대신 다음을 사용할 수 있습니다.

@Html.DropDownList("type",                  
Enum.GetValues(typeof(CompanyType)).Cast<CompanyType>()
.Select(x => new SelectListItem {Text = x.ToDescription(), Value = x.ToString()}))

이렇게 하면 드롭다운에 열거 값 대신 Description이 표시될 수 있습니다.또한 Edit의 경우 페이지 게시 후 드롭다운 선택 값에 따라 모델이 업데이트됩니다.

다른 사용자가 이미 말했듯이 상황에 따라 다른 에넘에 바인딩할 필요가 없는 한 열거에 데이터베이스를 바인딩하지 마십시오.여기에는 몇 가지 방법이 있습니다.다음의 몇 가지 예를 제시하겠습니다.

오브젝트 데이터 원본

ObjectDataSource를 사용한 선언적 방법.먼저 목록을 반환하고 DropDownList를 바인딩하는 BusinessObject 클래스를 만듭니다.

public class DropDownData
{
    enum Responses { Yes = 1, No = 2, Maybe = 3 }

    public String Text { get; set; }
    public int Value { get; set; }

    public List<DropDownData> GetList()
    {
        var items = new List<DropDownData>();
        foreach (int value in Enum.GetValues(typeof(Responses)))
        {
            items.Add(new DropDownData
                          {
                              Text = Enum.GetName(typeof (Responses), value),
                              Value = value
                          });
        }
        return items;
    }
}

그런 다음 ASPX 페이지에 HTML 마크업을 추가하여 다음 BO 클래스를 가리킵니다.

<asp:DropDownList ID="DropDownList1" runat="server" 
    DataSourceID="ObjectDataSource1" DataTextField="Text" DataValueField="Value">
</asp:DropDownList>
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server" 
    SelectMethod="GetList" TypeName="DropDownData"></asp:ObjectDataSource>

이 옵션은 뒤에 코드가 필요 없습니다.

Data Bind의 배후에 있는 코드

ASPX 페이지에서 HTML을 최소화하고 코드 배후에 바인드하려면 다음 절차를 수행합니다.

enum Responses { Yes = 1, No = 2, Maybe = 3 }

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        foreach (int value in Enum.GetValues(typeof(Responses)))
        {
            DropDownList1.Items.Add(new ListItem(Enum.GetName(typeof(Responses), value), value.ToString()));
        }
    }
}

어쨌든, Enum 타입의 메서드 GetValues, GetNames 등이 기능하도록 하는 것이 요령입니다.

ASP에서 어떻게 해야 할지 모르겠어요.NET 하지만 게시물을 보세요...도움이 될까요?

Enum.GetValues(typeof(Response));

linq를 사용할 수 있습니다.

var responseTypes= Enum.GetNames(typeof(Response)).Select(x => new { text = x, value = (int)Enum.Parse(typeof(Response), x) });
    DropDownList.DataSource = responseTypes;
    DropDownList.DataTextField = "text";
    DropDownList.DataValueField = "value";
    DropDownList.DataBind();
Array itemValues = Enum.GetValues(typeof(TaskStatus));
Array itemNames = Enum.GetNames(typeof(TaskStatus));

for (int i = 0; i <= itemNames.Length; i++)
{
    ListItem item = new ListItem(itemNames.GetValue(i).ToString(),
    itemValues.GetValue(i).ToString());
    ddlStatus.Items.Add(item);
}
public enum Color
{
    RED,
    GREEN,
    BLUE
}

ddColor.DataSource = Enum.GetNames(typeof(Color));
ddColor.DataBind();

정답 6을 사용하는 일반 코드입니다.

public static void BindControlToEnum(DataBoundControl ControlToBind, Type type)
{
    //ListControl

    if (type == null)
        throw new ArgumentNullException("type");
    else if (ControlToBind==null )
        throw new ArgumentNullException("ControlToBind");
    if (!type.IsEnum)
        throw new ArgumentException("Only enumeration type is expected.");

    Dictionary<int, string> pairs = new Dictionary<int, string>();

    foreach (int i in Enum.GetValues(type))
    {
        pairs.Add(i, Enum.GetName(type, i));
    }
    ControlToBind.DataSource = pairs;
    ListControl lstControl = ControlToBind as ListControl;
    if (lstControl != null)
    {
        lstControl.DataTextField = "Value";
        lstControl.DataValueField = "Key";
    }
    ControlToBind.DataBind();

}

이 답을 찾은 후, 저는 이것을 하는 더 좋은 방법(적어도 더 우아한)을 생각해 냈습니다. 다시 돌아와서 여기에 공유해야겠다고 생각했습니다.

페이지_로드:

DropDownList1.DataSource = Enum.GetValues(typeof(Response));
DropDownList1.DataBind();

로드 값:

Response rIn = Response.Maybe;
DropDownList1.Text = rIn.ToString();

값 저장:

Response rOut = (Response) Enum.Parse(typeof(Response), DropDownList1.Text);

이것은 아마 오래된 질문일 것이다.저는 이렇게 했어요.

모델:

public class YourEntity
{
   public int ID { get; set; }
   public string Name{ get; set; }
   public string Description { get; set; }
   public OptionType Types { get; set; }
}

public enum OptionType
{
    Unknown,
    Option1, 
    Option2,
    Option3
}

그런 다음 보기: 드롭다운을 채우는 방법을 보여 줍니다.

@Html.EnumDropDownListFor(model => model.Types, htmlAttributes: new { @class = "form-control" })

열거 목록의 모든 항목이 채워집니다.이게 도움이 됐으면 좋겠는데..

이것은 당신이 원하는 것은 아니지만 도움이 될 수 있습니다.

http://blog.jeffhandley.com/archive/2008/01/27/enum-list-dropdown-control.aspx

모든 listControlle을 통과하기 위해 다음과 같이 사용하면 어떨까요?


public static void BindToEnum(Type enumType, ListControl lc)
        {
            // get the names from the enumeration
            string[] names = Enum.GetNames(enumType);
            // get the values from the enumeration
            Array values = Enum.GetValues(enumType);
            // turn it into a hash table
            Hashtable ht = new Hashtable();
            for (int i = 0; i < names.Length; i++)
                // note the cast to integer here is important
                // otherwise we'll just get the enum string back again
                ht.Add(names[i], (int)values.GetValue(i));
            // return the dictionary to be bound to
            lc.DataSource = ht;
            lc.DataTextField = "Key";
            lc.DataValueField = "Value";
            lc.DataBind();
        }
And use is just as simple as :

BindToEnum(typeof(NewsType), DropDownList1);
BindToEnum(typeof(NewsType), CheckBoxList1);
BindToEnum(typeof(NewsType), RadoBuuttonList1);

그 후 ASP.NET은 몇 가지 기능으로 업데이트되었으며, 이제 삽입 열거형을 사용하여 드롭다운할 수 있습니다.

Enum 자체에 바인드하려면 다음 명령을 사용합니다.

@Html.DropDownList("response", EnumHelper.GetSelectList(typeof(Response)))

응답 인스턴스에서 바인딩하는 경우 다음을 사용합니다.

// Assuming Model.Response is an instance of Response
@Html.EnumDropDownListFor(m => m.Response)

ASP.NET Core에서는 마이크로소프트에서 제공하는 다음 HTML 도우미를 사용할 수 있습니다.AspNetCore.MVC.렌더링):

<select asp-items="Html.GetEnumSelectList<GridReportingStatusFilters>()">
     <option value=""></option>
</select>

이것은 LINQ를 사용하여 Enum과 DataBind(텍스트와 값)를 드롭다운으로 주문하기 위한 솔루션입니다.

var mylist = Enum.GetValues(typeof(MyEnum)).Cast<MyEnum>().ToList<MyEnum>().OrderBy(l => l.ToString());
foreach (MyEnum item in mylist)
    ddlDivisao.Items.Add(new ListItem(item.ToString(), ((int)item).ToString()));

커스텀 헬퍼 「ASP」의 작성에 관한 제 투고를 확인해 주세요.NET MVC - enums용 Drop Down List 도우미 작성" : http://blogs.msdn.com/b/stuartleeks/archive/2010/05/21/asp-net-mvc-creating-a-dropdownlist-helper-for-enums.aspx

콤보 박스(또는 다른 컨트롤)에 알기 쉬운 설명을 표시하려면 다음 기능과 함께 Description 속성을 사용할 수 있습니다.

    public static object GetEnumDescriptions(Type enumType)
    {
        var list = new List<KeyValuePair<Enum, string>>();
        foreach (Enum value in Enum.GetValues(enumType))
        {
            string description = value.ToString();
            FieldInfo fieldInfo = value.GetType().GetField(description);
            var attribute = fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false).First();
            if (attribute != null)
            {
                description = (attribute as DescriptionAttribute).Description;
            }
            list.Add(new KeyValuePair<Enum, string>(value, description));
        }
        return list;
    }

다음은 Description 속성이 적용된 열거형 예입니다.

    enum SampleEnum
    {
        NormalNoSpaces,
        [Description("Description With Spaces")]
        DescriptionWithSpaces,
        [Description("50%")]
        Percent_50,
    }

그럼 이렇게 조종에 바인드...

        m_Combo_Sample.DataSource = GetEnumDescriptions(typeof(SampleEnum));
        m_Combo_Sample.DisplayMember = "Value";
        m_Combo_Sample.ValueMember = "Key";

이렇게 하면 변수 이름처럼 보이지 않고 원하는 텍스트를 드롭다운에 넣을 수 있습니다.

확장 메서드를 사용할 수도 있습니다.확장에 익숙하지 않은 사용자에게는 VB 및 C# 문서를 확인하는 것이 좋습니다.


VB 확장:

Namespace CustomExtensions
    Public Module ListItemCollectionExtension

        <Runtime.CompilerServices.Extension()> _
        Public Sub AddEnum(Of TEnum As Structure)(items As System.Web.UI.WebControls.ListItemCollection)
            Dim enumerationType As System.Type = GetType(TEnum)
            Dim enumUnderType As System.Type = System.Enum.GetUnderlyingType(enumType)

            If Not enumerationType.IsEnum Then Throw New ArgumentException("Enumeration type is expected.")

            Dim enumTypeNames() As String = System.Enum.GetNames(enumerationType)
            Dim enumTypeValues() As TEnum = System.Enum.GetValues(enumerationType)

            For i = 0 To enumTypeNames.Length - 1
                items.Add(New System.Web.UI.WebControls.ListItem(saveResponseTypeNames(i), TryCast(enumTypeValues(i), System.Enum).ToString("d")))
            Next
        End Sub
    End Module
End Namespace

내선번호를 사용하려면:

Imports <projectName>.CustomExtensions.ListItemCollectionExtension

...

yourDropDownList.Items.AddEnum(Of EnumType)()

C# 확장:

namespace CustomExtensions
{
    public static class ListItemCollectionExtension
    {
        public static void AddEnum<TEnum>(this System.Web.UI.WebControls.ListItemCollection items) where TEnum : struct
        {
            System.Type enumType = typeof(TEnum);
            System.Type enumUnderType = System.Enum.GetUnderlyingType(enumType);

            if (!enumType.IsEnum) throw new Exception("Enumeration type is expected.");

            string[] enumTypeNames = System.Enum.GetNames(enumType);
            TEnum[] enumTypeValues = (TEnum[])System.Enum.GetValues(enumType);

            for (int i = 0; i < enumTypeValues.Length; i++)
            {
                items.add(new System.Web.UI.WebControls.ListItem(enumTypeNames[i], (enumTypeValues[i] as System.Enum).ToString("d")));
            }
        }
    }
}

내선번호를 사용하려면:

using CustomExtensions.ListItemCollectionExtension;

...

yourDropDownList.Items.AddEnum<EnumType>()

선택한 항목을 동시에 설정하려면 를 바꿉니다.

items.Add(New System.Web.UI.WebControls.ListItem(saveResponseTypeNames(i), saveResponseTypeValues(i).ToString("d")))

와 함께

Dim newListItem As System.Web.UI.WebControls.ListItem
newListItem = New System.Web.UI.WebControls.ListItem(enumTypeNames(i), Convert.ChangeType(enumTypeValues(i), enumUnderType).ToString())
newListItem.Selected = If(EqualityComparer(Of TEnum).Default.Equals(selected, saveResponseTypeValues(i)), True, False)
items.Add(newListItem)

시스템으로 변환합니다.Enum 대신 int 크기 및 출력 문제를 회피합니다.예: 0xFFFF0000은 uint로 4294901760이지만 int로 -65536이 됩니다.

TryCast 및 as System.Enum이 Convert보다 약간 빠릅니다.ChangeType(enumTypeValues[i], enumUnderType).ToString() (속도 테스트에서는 12:13).

콤보 박스와 드롭다운 리스트가 있는 asp.net 및 winforms 튜토리얼:C# WinForms 및 ASP에서 콤보박스와 Enum을 사용하는 방법.

도움이 되기를 바라다

인정되고 있는 솔루션은 동작하지 않지만, 이하의 코드는 최단의 솔루션을 찾는 다른 사용자에게 도움이 됩니다.

 foreach (string value in Enum.GetNames(typeof(Response)))
                    ddlResponse.Items.Add(new ListItem()
                    {
                        Text = value,
                        Value = ((int)Enum.Parse(typeof(Response), value)).ToString()
                    });

이거 좀 더 짧게 할 수 있어요.

public enum Test
    {
        Test1 = 1,
        Test2 = 2,
        Test3 = 3
    }
    class Program
    {
        static void Main(string[] args)
        {

            var items = Enum.GetValues(typeof(Test));

            foreach (var item in items)
            {
                //Gives you the names
                Console.WriteLine(item);
            }


            foreach(var item in (Test[])items)
            {
                // Gives you the numbers
                Console.WriteLine((int)item);
            }
        }
    }

드롭 앤 엔럼으로 동작하는 C# 솔루션을 원하는 고객에게는...

private void LoadConsciousnessDrop()
{
    string sel_val = this.drp_Consciousness.SelectedValue;
    this.drp_Consciousness.Items.Clear();
    string[] names = Enum.GetNames(typeof(Consciousness));
    
    for (int i = 0; i < names.Length; i++)
        this.drp_Consciousness.Items.Add(new ListItem(names[i], ((int)((Consciousness)Enum.Parse(typeof(Consciousness), names[i]))).ToString()));

    this.drp_Consciousness.SelectedValue = String.IsNullOrWhiteSpace(sel_val) ? null : sel_val;
}

이 투고가 오래된 Asp.net용이라는 것은 알고 있습니다만, 최근 c# Windows Forms Project에서 사용한 솔루션을 제공하고 싶었습니다.여기서 키는 열거된 요소의 이름이고 값은 열거된 값인 사전을 구축하는 것이 아이디어입니다.그런 다음 사전을 콤보 상자에 바인딩합니다.ComboBox 및 Enum Type을 인수로 사용하는 일반 함수를 참조하십시오.

    private void BuildComboBoxFromEnum(ComboBox box, Type enumType) {
        var dict = new Dictionary<string, int>();
        foreach (var foo in Enum.GetValues(enumType)) {
            dict.Add(foo.ToString(), (int)foo);
        }
        box.DropDownStyle = ComboBoxStyle.DropDownList; // Forces comboBox to ReadOnly
        box.DataSource = new BindingSource(dict, null);
        box.DisplayMember = "Key";
        box.ValueMember = "Value";
        // Register a callback that prints the Name and Value of the 
        // selected enum. This should be removed after initial testing.
        box.SelectedIndexChanged += (o, e) => {
            Console.WriteLine("{0} {1}", box.Text, box.SelectedValue);
        };
    }

이 기능은 다음과 같이 사용할 수 있습니다.

BuildComboBoxFromEnum(comboBox1,typeof(Response));

언급URL : https://stackoverflow.com/questions/61953/how-do-you-bind-an-enum-to-a-dropdownlist-control-in-asp-net

반응형