Preselect an Item in a MVC DropDownList
Please suggest what is wrong in this code. I am unable to select an item
@{
ViewBag.Title = "Users";
objUser user = (objUser)Session["userdet"];
}
@Html.DropDownListFor(model => model.User, new Select开发者_JAVA技巧List(Model.UserList, "Id", "Name", user.Id))
Also should I use DropDownListFor or DropDownLisT?
The problem is in the code "model => model.User".
What is ".User" set to? If it is not == user.Id, then the code won't work. I think model.User is overriding "user.Id" on the end of the statement so "user.UserId" does not make sense
John Stuntz is correct, the xxxFor helpers don' take the Selected property in the SelectListItem (contained in the SelectList object) into account. What you can do in your controller is:
model.User = user.id;
return View();
and in your view:
@Html.DropDownListFor(model => model.User, new SelectList(Model.UserList, "Id", "Name"))
精彩评论