我有SelectList
:
ViewData["Agency"] = new SelectList(db.Agencies.AsNoTracking().OrderBy(_ => _.AgencyID), "AgencyId", "Name");
我需要选择默认值,我试试这个:
ViewData["Agency"] = new SelectList(db.Agencies.AsNoTracking().OrderBy(_ => _.AgencyID), "AgencyId", "Name",999);
而且:
var valueSelected = db.Agencies.AsNoTracking().Where(_=>_.AgencyId == 999).First();
ViewData["Agency"] = new SelectList(db.Agencies.AsNoTracking().OrderBy(_ => _.AgencyID), "AgencyId", "Name",valueSelected );
答案 0 :(得分:0)
默认情况下,您需要将AgentID
传递给SelectList
构造函数进行设置:
var valueSelected = db.Agencies.AsNoTracking().Where(=>.AgencyId == 999).First();
现在在SelectList中:
ViewData["Agency"] = new SelectList(db.Agencies.AsNoTracking().OrderBy(_ => _.AgencyID), "AgencyId", "Name",valueSelected.AgencyId );
答案 1 :(得分:0)
尝试使用FirstOrDefault()
代替First()
。
var valueSelected = db
.Agencies.AsNoTracking()
.Where(_=>_.AgencyId == 999)
.FirstOrDefault();
ViewData["Agency"] = new SelectList(db.Agencies.AsNoTracking()
.OrderBy(_ => _.AgencyID), "AgencyId", "Name",valueSelected );