ASP.NET MVC3 Html.DropDownListFor数据绑定和选中指定项

1.DropDownListFor数据绑定

①.在Action中查询要绑定到DropDownListFor的数据,并赋值给ViewBag:

public ActionResult Create()
{
    ViewBag.Categories = new SelectList(db.Category, "Id", "Name");
    return View();
}

②.在View中将数据绑定到DropDownListFor:

@Html.DropDownListFor(model => model.CategoryId, ViewBag.Categories as IEnumerable<SelectListItem>);



2.DropDownListFor选中指定项

这需要在SelectList构造函数中设置,例如:

public ActionResult Create()
{
    ViewBag.Categories = new SelectList(db.Category, "Id", "Name", "2");
    return View();
}


评论: 0 | 引用: 0 | 查看次数: 10449
发表评论
登录后再发表评论!