Can't get my DropDownListFor to select a selected SelectListItem item in a Dropdown menu

戏子无情 提交于 2019-12-31 02:45:49

问题


I have a collection of items populated to a drop down menu:

string myUserName = "PopulatedWithSomeUser";

var users= from x in userRepository.GetAll()
    select new SelectListItem
       {
          Value = x.Id.ToString(),
          Text = x.Name,
          Selected = (x.Name == myUserName )
       };

This correctly populates an object and sets the selected item. Next I pass this to my View with a ViewModel and try to Populate/select:

I tried:

   @Html.DropDownListFor(model=>model.Users,new SelectList(Model.Users),new {id = "add-user-list", name="add-user-list"})

also

@Html.DropDownListFor(model=>model.Users,new SelectList(Model.Users,"Value","Text","Selected"),new {id = "add-user-list", name="add-user-list"})

also

@Html.DropDownListFor(model=>model.Users,Model.Users, new {id = "add-user-list", name="add-user-list"})

The list is populated correctly but my "selected" item is never selected. What am I doing wrong ? Thanks.


回答1:


As a first parameter you should pass a field for what you are going to receive data after form submit. Everything else looks right:

@Html.DropDownListFor(model=>model.UserId, Model.Users)

Or if you are going to provide your own id and name - it would be better to use this (msdn):

@Html.DropDownList("add-user-list", Model.Users, new {id = "add-user-list"})


来源:https://stackoverflow.com/questions/11039621/cant-get-my-dropdownlistfor-to-select-a-selected-selectlistitem-item-in-a-dropd

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!