tags:

views:

82

answers:

2

Hi

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

A: 

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.

SLaks
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
+1  A: 

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;
}
Francisco
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
public interface IList : ICollection, IEnumerableSo I think that it's ok to do that cast. But don't know why it works with dropdownlist though....
Francisco