在MVC C#中的SelectList中设置默认值

时间:2015-04-23 14:24:19

标签: c# asp.net-mvc selectlist

我有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 );

2 个答案:

答案 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 );