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
  • 32,195
  • 56
  • 190
  • 305

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
  • 994,864
  • 265
  • 3,241
  • 2,902
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,435
  • 2
  • 25
  • 27