views:

612

answers:

1

give me full demonstration of html.dropdownlist how it is implimented? how to set values in the list? how to use it in .aspx and in controller file?

+1  A: 

Ok, let me have a try

There is SelectList class that you can use to create a list in the controller class (in the approriate controller action) as follows:

var items = new KeyValueList();
var item = new KeyValue() {Key = 1, Value = "Orange" };    
items.Add(item);
item = new KeyValue() {Key = 2, Value = "Apple" };    
items.Add(item);

var myList = new SelectList(items, "Key", "Value", selectedItemId);

The selectedItemId will be the value of an item's key. Then add myList to the ViewData collection with a key that you can use to refer to it from the View. Like:

ViewData["FruitList"] = myList;

In the View, you can then use:

            <p>
              <label for="FruitList">Fruits:</label>
              <%= Html.DropDownList("FruitList") %>
            </p>

On postback to the controller action, the "Key" for the selected value is sent as part of formcollection or post parameters, and you can access the value using the "FruitList".

Gboyega S.
What namespace contains KeyValueList?
rotary_engine