简体   繁体   中英

How to specify “value” for asp.net mvc Html helper droplist

I want to specify a value for each option in the my select list box but I am generating it with an html helper.

So I have this

<%= Html.DropDownList("DropDownList") %>  

// controller

ViewData["DropDownList"] = new SelectList(MyClass.GenerateListBox());

// MyClass

        public static List<string> GenerateListBox()
        {
            List<string> listBox= new List<string>();
            listBox.Add("Bye");
            listBox.Add("hi");
            listBox.Add("something");

            return listBox;
        }

So I see that SelectList has a "stringDataField" but it is only a stringnot a list so now really sure what I have to change.

Do I have to make some sort of other list?

Thanks

Use this constructor instead:

ViewData["DropDownList"] = new SelectList(GenerateListBox(), "Value", "Text");

public static List<SelectListItem> GenerateListBox()
{
    List<SelectListItem> listBox = new List<SelectListItem>();
    listBox.Add(new SelectListItem { Text = "bye", Value = "byeValue" });
    listBox.Add(new SelectListItem { Text = "hi", Value = "hiValue" });
    listBox.Add(new SelectListItem { Text = "something", Value = "somethingValue" });

    return listBox;
}

Use the SelectList constructor that takes two strings .

Specifically, instead of giving it a list of strings, give it a list of some object that has DisplayName and Value properties (for example, KeyValuePair<String, String> , though I would recommend something more specific), and pass the names of those properties to that constructor. This will set the DataTextField and DataValueField properties.

EDIT : What I mean is that instead of making your GenerateListBox method return a List<String> , you should make it return a List<YourClass> and make a YourClass class with properties for the DisplayName and the Value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM