Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC SelectList not working

Tags:

asp.net-mvc

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?

like image 535
mamu Avatar asked Jun 28 '09 15:06

mamu


4 Answers

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;
like image 97
John Foster Avatar answered Nov 15 '22 08:11

John Foster


You could have also simply changed the one line from:

SelectList selectList = new SelectList(items);

to

SelectList selectList = new SelectList(items, "Text", "Value");

This will instruct MVC which properties to use as the Text and Value in your option tags.

like image 22
Matt Cofer Avatar answered Nov 15 '22 06:11

Matt Cofer


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" })%>
like image 23
griegs Avatar answered Nov 15 '22 06:11

griegs


If you look at the Intellisense for the SelectList constructor overloads, the code SelectList(items) should work, but doesn't. The fact that it simply does a ToString() on items is, as far as I can tell, a bug that Microsoft should fix. The answers are all nice workarounds. BTW, if you use the method supplying "Text" and "Value", the correct answer should be

 SelectList selectList = new SelectList(items, "Value", "Text")

not

SelectList selectList = new SelectList(items, "Text", "Value")

At least, that agrees with my experimentation in MVC 3.

like image 35
sorgfelt Avatar answered Nov 15 '22 07:11

sorgfelt