Reputation: 87
So I have this in my view(I have broken it out into a foreach so I could debug it properly). And according to the objects that are created it looks good. I get 1 item that has the selected true.
@{
var useritems = new List<SelectListItem>();
foreach (var si in Model.UserList)
{
if (Model.CurrentUser.Id.Equals(si.Id))
{
useritems.Add(new SelectListItem { Selected = true, Text = si.Username, Value = si.Id.ToString(CultureInfo.InvariantCulture) });
}
else
{
useritems.Add(new SelectListItem { Text = si.Username, Value = si.Id.ToString(CultureInfo.InvariantCulture) });
}
}
}
What I want to do here is check for the current(logged on) user and set the select default to him/her.
@Html.DropDownListFor(model => model.Creator, useritems, new { id = "CreatorDDL", })
This does not however set any of the objects in useritems to selected. Even tho in the debugger it shows that 1 item has selected: true
Somehow it just shows the first item in the list. Any ideas? or am I just tired and missing something really easy?
Upvotes: 0
Views: 436
Reputation: 12491
Set model.Creator
value in addition to Selected
in SelectList
.
model.Creator = Model.CurrentUser.Id;
It's better to do such things in your Controller
, not in your View
.
Upvotes: 1