2

Possible Duplicate:
How can I get this ASP.NET MVC SelectList to work?

What the hell is it? Is there some kind of a bug in DropDownList of MVC3? SelectedValue doesn't show up as actually selected in the markup.

I am trying different approaches, nothing works.

public class SessionCategory
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public static IEnumerable<SessionCategory> Categories
{
     get
      {
          var _dal = new DataLayer();
          return _dal.GetSesionCategories();
      }
}

@{
        var cats = Infrastructure.ViewModels.Session.Categories;
        var sl = new SelectList(cats, "Id", "Name",2);
}
@Html.DropDownList("categories", sl);
Community
  • 1
  • 1
iLemming
  • 34,477
  • 60
  • 195
  • 309

2 Answers2

8

Try the following:

Model:

public class MyViewModel
{
    public int CategoryId { get; set; }
    public IEnumerable<SelectListItem> Categories { get; set; }
}

Controller:

public ActionResult Foo()
{
    var cats = _dal.GetSesionCategories();
    var model = new MyViewModel
    {
        // Preselect the category with id 2
        CategoryId = 2,

        // Ensure that cats has an item with id = 2
        Categories = cats.Select(c => new SelectListItem
        {
            Value = c.Id.ToString(),
            Text = c.Name
        })
    };
}

View:

@Html.DropDownListFor(
    x => x.CategoryId,
    new SelectList(Model.Categories, "Value", "Text")
)
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
6

I think you need to make the selected value a string. There's also some value in using extension methods as detailed here.

Community
  • 1
  • 1
Timbo
  • 4,505
  • 2
  • 26
  • 29