C# MVC-在ViewModel内设置SelectList的选定值
在没有selectedvalue的情况下实例化SelectList后,如何设置其selectedvalue属性 控制器C# MVC-在ViewModel内设置SelectList的选定值,c#,asp.net-mvc,selectlist,C#,Asp.net Mvc,Selectlist,在没有selectedvalue的情况下实例化SelectList后,如何设置其selectedvalue属性 控制器 var _walkInnVM = new WalkInnVM { ProspectHandledEmpList = new SelectList(_db.Employees .AsEnumerable() .Where(e => e.Id == Int32.Parse(Session["LoggedUserId"].
var _walkInnVM = new WalkInnVM
{
ProspectHandledEmpList = new SelectList(_db.Employees
.AsEnumerable()
.Where(e => e.Id == Int32.Parse(Session["LoggedUserId"].ToString()))
.ToList(), "Id", "Name")
};
HTML
@Html.DropDownListFor(m => m.ProspectHandledEmpID,
Model.ProspectHandledEmpList, "",
new { @class = "form-control select2 ", @id = "ddlProspectHandled" })
在将其传递到视图之前,需要在模型中设置
ProspectHandledEmpID
的值
var _walkInnVM = new WalkInnVM
{
ProspectHandledEmpID = someValue, // add this
ProspectHandledEmpList = new SelectList(_db.Employees.AsEnumerable()
.Where(e => e.Id == Int32.Parse(Session["LoggedUserId"].ToString())), "Id", "Name")
};
如果
db.Employees
包含Id
值为1到10的项目,并且您设置了值ProspectHandledEmpID=3
,然后,在第一次生成视图时,将选择第三个选项。是否要为选择列表设置默认值?只需设置prospectHandleTempId的值即可-这就是模型绑定的工作方式。而且设置Selected
属性毫无意义,因为它会被忽略。另外请注意,您不需要.ToList()
-这只是不必要的开销。@StephenMuecke一个小例子会很有帮助。@ViniVasundharan是的。.这就是我要找的。.在GET方法中,在将模型传递到视图之前,只需将prospectHandleTempId
的值设置为与其中一个Employee.Id
值相匹配,模型就会被选中;返回视图(_walkinvm)代码>如果可能,请查看