开发者

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"))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜