2013-08-23 16 views
0

vs'12 asp.net C#MVC4 EF代码第一问题在控制器转换类型新selectitemlist

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<SelectListItem>'.

我一直在试图转换这个查询到IEnumerable<SelectListItem>就像疯了一样,如果任何人都可以帮我转换这个正确的方式,我会很感激它。

另外,如果我没讲清楚,就是我做的是用户的列表,从LINQ查询是不是“管理”角色,我想显示他们DropDrownList

编辑:视图

@model OG.Models.UserProfiles

再后来

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

+1

你可以发布在你的视图中引用'ViewBag.DDLRoles'的代码吗? –

+0

请发表您的看法。 – ataravati

+0

检查我的答案在http://stackoverflow.com/questions/17951524/mvc-and-entity-framework-select-list/17953161#17953161 –

回答

1

您认为应该是这样的:

@model OG.Models.UserProfiles 

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

而且,在你的控制器,你必须:

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

ViewBag.DDLRoles = adminUsers; 

这会将所选用户的UserID从DropDownList提交到你的行动。顺便说一下,请为您的模型选择更有意义的名称。您的“UserProfiles”模型应该被称为“UserProfile”或“User”,因为它仅代表一个用户,而不代表用户的集合。

+0

错误:'System.Web.Mvc.SelectListItem'不包含名称为'UserID'的属性 - 在视图 –

+0

这里没有SelectListItem。你使用我的代码还是Jason的代码?请确保Controller和View中的代码与我答案中的代码相同。 – ataravati

+0

并确保UserProfiles类具有名为UserID的属性(主键)。 – ataravati

1

第二个参数必须是一个IEnumerable<SelectListItem>,这样的事情:

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

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

仍然收到'不能隐式转换类型'System.Web.Mvc.SelectList'到'System.Collections.Generic.List ''如果它在控制器中转换或在视图中 –

+0

什么行给出这个错误? –

+0

这是我的错,你的代码跑了,只要我去正确的行动。 –