【问题标题】:Issues converting types to new selectitemlist将类型转换为新的 selectitemlist 的问题
【发布时间】:2013-08-23 17:12:43
【问题描述】:

vs'12 asp.net C# MVC4 EF代码优先

在控制器中

var usernames = Roles.GetUsersInRole("Admin");
var adminUsers = db.UserProfiles
                 .Where(x => !usernames.Contains(x.UserName)).ToList();

List<UserProfiles> myList = adminUsers.ToList();
IEnumerable<UserProfiles> myEnumerable = myList;

ViewBag.DDLRoles = myEnumerable;

进入视图状态的错误

The ViewData item that has the key 'DDLRoles' is of type 'System.Collections.Generic.List'1[[OG.Models.UserProfiles, OG, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]' but must be of type 'IEnumerable&lt;SelectListItem&gt;'.

我一直在尝试将此查询转换为 IEnumerable&lt;SelectListItem&gt; 疯狂,如果有人可以帮助我以正确的方式转换它,我将不胜感激。

另外,如果我没有说清楚,我正在做的是从 linq 查询中获取不属于 "Admin" 角色的用户列表,我正在尝试将它们显示在里面一个 DropDrownList

编辑:视图

@model OG.Models.UserProfiles

后来

@Html.DropDownList("DDLRoles", (SelectList)ViewData["SelectedValue"])

【问题讨论】:

  • 你能贴出你认为引用ViewBag.DDLRoles的代码吗?
  • 请发表您的看法。
  • 那么,传递给视图的模型是 UserProfiles 类型的吗?而且,您的视图中只有 DropDownList 吗?
  • @ataravati 是的,没错,传递模型(因为我不知道如何转换它)并且视图中只有 1 个 DDL

标签: asp.net-mvc casting type-conversion


【解决方案1】:

你的视图应该是这样的:

@model OG.Models.UserProfiles

@Html.DropDownListFor(model => model.UserID, new SelectList(ViewBag.DDLRoles, "UserID", "UserName", Model.UserID))

而且,在您的 Controller 中,您将拥有:

var usernames = Roles.GetUsersInRole("Admin");
var adminUsers = db.UserProfiles
                 .Where(x => !usernames.Contains(x.UserName)).ToList();

ViewBag.DDLRoles = adminUsers;

这会将 DropDownList 中所选用户的 UserID 提交到您的操作。顺便说一句,请为您的模型选择更有意义的名称。您的“UserProfiles”模型应称为“UserProfile”或“User”,因为它仅代表一个用户,而不是一组用户。

【讨论】:

  • 错误:System.Web.Mvc.SelectListItem' does not contain a property with the name 'UserID' - 在视图中
  • 这里没有 SelectListItem。你用的是我的代码还是 Jason 的代码?请确保您的控制器和视图中的代码与我的答案中的代码相同。
  • 并且,确保 UserProfiles 类有一个名为 UserID 的属性(主键)。
  • 效果很好,我如何从我的 HTTPPost 控制器的 ddl 中获取这些数据?
  • 嗯,你要做什么不是很清楚。为什么你有一个只有一个 DropDownList 的视图?你能解释一下这段代码应该做什么吗?
【解决方案2】:

第二个参数需要是IEnumerable&lt;SelectListItem&gt;,类似这样:

@{
    List<UserProfiles> Users = ViewBag.DDLRoles;
}

@Html.DropDownList("Users", Users.Select(x => new SelectListItem() { Text = x.UserName, Value = x.UserName }));

【讨论】:

  • 如果在控制器或视图中转换,仍会收到Cannot implicitly convert type 'System.Web.Mvc.SelectList' to 'System.Collections.Generic.List&lt;OG.Models.UserProfiles&gt;'
  • 这是我的错,你的代码运行时也发现了,只要我采取了正确的行动。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-16
  • 1970-01-01
  • 2012-04-18
  • 1970-01-01
  • 2011-11-17
相关资源
最近更新 更多