不能让我的DropDownListFor在下拉菜单选择所选SelectListItem项目 [英] Can't get my DropDownListFor to select a selected SelectListItem item in a Dropdown menu

查看:363
本文介绍了不能让我的DropDownListFor在下拉菜单选择所选SelectListItem项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要填充一个下拉菜单项的集合:

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:

我试过:

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

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

@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.

推荐答案

作为第一个参数,你应该通过一个字段为您准备后提交表单接收数据的内容。其他的一切看起来正确的:

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)

或者,如果你要提供自己的ID和名称 - 这将是更好地使用它(的 MSDN ):

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

这篇关于不能让我的DropDownListFor在下拉菜单选择所选SelectListItem项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆