tags:

views:

835

answers:

4
List<SelectListItem> items = new List<SelectListItem>();
if (a)
{
    SelectListItem deliveryItem = new SelectListItem()
    {
        Selected = a.selected,
        Text = "Delivery",
        Value = "1"
    };

    items.Add(deliveryItem);
}

if (b)
{
    SelectListItem pickupItem = new SelectListItem()
    {
        Selected = b.selected,
        Text = "Pickup",
        Value = "2"
    };

    items.Add(pickupItem);
}

SelectList selectList = new SelectList(items);

ViewData["OrderTypeList"] = selectList;

then

using it with Html.DropDownList("OrderTypeList") renders

<select id="OrderTypeList" name="OrderTypeList"><option>System.Web.Mvc.SelectListItem</option>
<option>System.Web.Mvc.SelectListItem</option>
</select>

Why it is not rendering options properly?

A: 

I think you should try rendering with

Html.DropDownList("OrderTypeList", ViewData["OrderTypeList"])
tdelev
I think i can use that if i have selectlist in viewdata. But here i am trying to build selectlist
mamu
+2  A: 

The constructor method you're calling when you do:

SelectList selectList = new SelectList(items);

Creates a set of SelectListItems that themselves point to SelectListItems (hence the weird option since it just calls ToString on the object). Instead set your list to the ViewData key directly

ViewData["OrderTypeList"] = items;
sighohwell
thanks, it solved the issue
mamu
A: 

Or you could create a class that will hold the select list and then return the class as the views model. I think that's a much more elegant way of doing it rather than ViewData.

public class MyFormViewModel
{
    public SelectList Friends { get; set; }
}

Then in your ActionResult

MyFormViewModel fvm = new MyFormViewModel();
fvm.Friends = new SelectList(myList, "UserName", "NickName");

Then in your view

<%= Html.DropDownList("ToUserName", Model.Friends, new { @class = "field" })%>
griegs
A: 

This article describes about how to bind dropdownlist:

http://www.altafkhatri.com/Technical/How%5Fto%5Fbind%5FIList%5Fwith%5FMVC%5FDropdownlist%5Fbox