DropDownList SelectList SelectedValue issue [duplicate]
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 开发者_如何学JAVAclass 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);
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")
)
I think you need to make the selected value a string. There's also some value in using extension methods as detailed here.
精彩评论