开发者

html helper html.dropdownlist in asp.net mvc

give me ful开发者_运维问答l 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?


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".

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜