将类型转换为新的selectitemlist时出现问题 [英] Issues converting types to new selectitemlist

查看:123
本文介绍了将类型转换为新的selectitemlist时出现问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先使用vs'12 asp.net C#MVC4 EF代码

vs'12 asp.net C# MVC4 EF code first

在控制器中

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;

该错误进入视图状态

具有键 DDLRoles的ViewData项的类型为 System.Collections.Generic.List 1 [[OG.Models.UserProfiles,OG,版本= 1.0 .0.0,Culture = neutral,PublicKeyToken = null]],但必须为 IEnumerable< SelectListItem>类型。

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

And i have been trying to convert this query to IEnumerable<SelectListItem> like crazy, If anyone can help me convert this the right way i'd appreciate it alot.

如果我不清楚的话,我正在做的是从linq查询中获取不是管理员 角色的用户列表我试图将它们显示在DropDrownList内

Also if i did not make it clear, what I'm doing is taking a list of users from the linq query that are NOT of "Admin" Roles and I am trying to display them inside of a DropDrownList

编辑:视图

@model OG.Models.UserProfiles

然后稍后

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

推荐答案

您的视图应如下所示:

@model OG.Models.UserProfiles

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

然后,在Controller中,您将拥有:

And, in your Controller, you'll have:

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

ViewBag.DDLRoles = adminUsers;

这会将选定用户的用户ID从DropDownList提交到您的操作。顺便说一句,请为您的模型选择更有意义的名称。您的 UserProfiles模型应称为 UserProfile或 User,因为它仅代表一个User,而不是Users的集合。

This will submit the UserID of the selected user from the DropDownList to your Action. By the way, please choose more meaningful names for your Models. Your "UserProfiles" Model should be called "UserProfile" or "User", because it represents one User only, not a collection of Users.

这篇关于将类型转换为新的selectitemlist时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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