How to specify “value” for 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>();

            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?


14.10.2009 00:35:13

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;
14.10.2009 05:45:39
Ah this is what I was looking for. I did the same thing you did but I did not put "Value", "Text" in the constructor. Kinda weird that you have to do it. I have another question since I did not know that with the constructor I did instead ViewData["DDL"] = (IEnumerator)GenerateListBox() and that worked. Why? I thought List implements IEnumerator?
chobo2 14.10.2009 17:40:58
public interface IList : ICollection, IEnumerable So I think that it's ok to do that cast. But don't know why it works with dropdownlist though....
Francisco 15.10.2009 16:53:02

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.

14.10.2009 00:54:47
How would I use the selectList constructor. Like I want each "value" to be different. and how I have my selectList it takes in a list of strings and makes the select list. So I would have to pass some how a list of strings for values too.
chobo2 14.10.2009 00:48:44