我有一个通过ViewBag变量填充的下拉列表,我想知道如何使用id值设置此列表的选定索引。
这是我创建ViewBag变量的地方,请注意id,这是我想用来设置列表中默认选定项目的内容:
var events = db.Events.Select(e => new
{
id = e.EventID,
Name = e.EventTitle
}).OrderBy(e => e.Name).ToList();
ViewBag.EventsList = new MultiSelectList(events, "id", "Name");
这是视图中的下拉列表:
@Html.DropDownList("id", (MultiSelectList)ViewBag.EventsList, new { @class = "form-control", id = "lstTopFeaturedEvent" })
无论如何我可以使用控制器中设置的id属性设置默认选择值吗?
答案 0 :(得分:1)
您应该使用视图模型并忘记ViewBag
将其视为不存在。你会看到事情会变得多么容易。所以定义一个视图模型:
public class MyViewModel
{
public int SelectedCategoryId { get; set; }
public IEnumerable<SelectListItem> Categories { get; set; }
}
然后从控制器填充此视图模型:
public ActionResult NewsEdit(int ID, dms_New dsn)
{
var dsn = (from a in dc.dms_News where a.NewsID == ID select a).FirstOrDefault();
var categories = (from b in dc.dms_NewsCategories select b).ToList();
var model = new MyViewModel
{
SelectedCategoryId = dsn.NewsCategoriesID,
Categories = categories.Select(x => new SelectListItem
{
Value = x.NewsCategoriesID.ToString(),
Text = x.NewsCategoriesName
})
};
return View(model);
}
最后在您的视图中使用强类型DropDownListFor
帮助程序:
@model MyViewModel
@Html.DropDownListFor(
x => x.SelectedCategoryId,
Model.Categories
)