Reputation: 4067
How can I set the selectedvalue property of a SelectList after it was instantiated without a selectedvalue.
Controller
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" })
Upvotes: 1
Views: 1346
Reputation:
You need to set the value of ProspectHandledEmpID
in the model before you pass it to the view
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")
};
If db.Employees
contains items with Id
values from 1 to 10 and you set the value ProspectHandledEmpID = 3
, then the 3rd option will be selected when the view is first generated.
Upvotes: 1