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

查看:35
本文介绍了无法让我的 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 )
       };

这将正确填充对象并设置所选项目.接下来,我使用 ViewModel 将其传递给我的 View 并尝试填充/选择:

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):

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

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

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