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?
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;
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.
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" })%>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With