15

I'm trying to populate a DropDownList with values pulled from a property, and my end result right now is a list of nothing but "System.Web.Mvc.SelectListItem"s. I'm sure there's some minor step I'm omitting here, but for the life of me I can't figure out what it is.

The property GET generating the list:

public IEnumerable<SelectListItem> AllFoo {
    get {
        var foo = from g in Bar
                  orderby g.name
                  select new SelectListItem {
                     Value = g.fooid.ToString(),
                     Text = g.name
                  };

        return foo.AsEnumerable();
    }
}

The controller code:

public ActionResult Edit(string id) {
    // n/a code
    ViewData["fooList"] = new SelectList(g.AllFoo, g.fooid);

    return View(g);
}

The view code:

<%= Html.DropDownListFor(model => model.fooid, ViewData["fooList"] as SelectList) %>

3 Answers 3

33

The problem here is that you shoudn't fill a SelectList with an IEnumerable<SelectListItem>. Use either SelectList or an IEnumerable<SelectListItem>, but not both. For more details, have a look at this question: Asp.Net MVC 2 Dropdown Displaying System.Web.MVC.SelectListItem

Sign up to request clarification or add additional context in comments.

Comments

2

I ran into the same problem. You should render your List in the view like

@Html.DropDownListFor(model => model.fooid, new 
    SelectList(ViewData["fooList"],"Text","Value", Model.DefaultValue))

This is based on c# with razor view

Comments

-5

EDIT: This question is very similar to one that was already asked:

ASP.NET MVC 2 - Html.DropDownListFor confusion with ViewModel


Otherwise, you might find this article helpful:

http://www.nickriggs.com/posts/rendering-and-binding-drop-down-lists-using-asp-net-mvc-2-editorfor/

It uses EditorFor, but the same can be done for DisplayFor.

2 Comments

this is not very helpful. this question asks for the specific reason why the <option> tags are rendered with nothing but "System.Web.Mvc.SelectListItem" in them instead of having proper text and value. Neither of your links addresses this particular problem.
Yeah, neither of those other questions or articles are "very similar" to this one. Not at all in fact.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.