可能的重复:
我怎样才能让这个 ASP.NET MVC SelectList 工作? https://stackoverflow.com/questions/781987/how-can-i-get-this-asp-net-mvc-selectlist-to-work
这到底是什么? MVC3的DropDownList是否存在某种错误?
SelectedValue 不会显示为标记中实际选择的值。
我正在尝试不同的方法,但没有任何效果。
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);
请尝试以下操作:
Model:
public class MyViewModel
{
public int CategoryId { get; set; }
public IEnumerable<SelectListItem> Categories { get; set; }
}
控制器:
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")
)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)