Razor操作Dropdownlist
目的:为Dropdownlist赋值,并获得项目选项值itemID
法一:
//项目列表
ViewData["ItemID"] = string.IsNullOrEmpty(itemID) ? "4" : itemID;
var Result = from a in db.Fee_Items
where a.CategoryID == 7 /*7是工作量*/
select new SelectListItem
{
Text = a.ItemName,
Value = a.ItemID
};
ViewData["ItemList"] = Result.Distinct();
调用:
@Html.DropDownList("ItemID", @ViewBag.ItemList as IEnumerable<SelectListItem>)
法二
//当前项目
ViewData["ItemID"] = string.IsNullOrEmpty(itemID) ? "4" : itemID;
//项目列表,参数为数据源,id值,显示文本,默认值
ViewData["ItemIist"] = new SelectList(db.Fee_Items.Where(X => X.CategoryID == 1 || X.CategoryID == 2), "ItemID", "ItemName", ViewData["ItemID"]);
调用: @Html.DropDownList("ItemID", ViewData["ItemIist"] as SelectList);