这是一个带有Identity Web应用程序的MVC5。我正在尝试在我的注册视图中添加一个下拉列表,这样当一个人注册自己时,他们可以选择自己的角色。我的Register View模型目前只有Department和Depot的下拉列表,但是当我尝试复制角色时它不起作用。
注意:我设想我的所有角色都在我的dbo.AspNetRoles表中,并且已分配给这些角色的所有用户都将在我的dbo.AspNetUserRoles表中。
我知道我需要做以下事情来实现这个目标,但我不确定我是否错过了任何东西:
添加(RoleList)以显示下拉列表中的对象
(ConfigureRegisterViewModel方法)以容纳角色ID
这是我在此行的AccountController中收到的错误
IEnumerable<RegisterViewModel> roles = db.Roles.OrderBy(u => u.Name);
无法隐式转换类型 'System.Linq.IOrderedQueryable' 至 'System.Collections.Generic.IEnumerable'。 存在显式转换(您是否错过了演员?)
作为MVC专家的人能否指出我如何做到这一点的正确方向?将来我将修改我的ApplicationUser类和这个RegisterViewModel来添加更多变量,例如:年龄,街道地址和工作位置等
这是我的RegisterViewModel的片段
public class RegisterViewModel
{
//RoleID
public int Id { get; set; }
[Required(AllowEmptyStrings = false)]
//RoleName
[Display(Name = "RoleName")]
public string Name { get; set; }
public IEnumerable<SelectListItem> RolesList { get; set; }
//Department and Depot
public int DepotID { get; set; }
public IEnumerable<SelectListItem> DepotList { get; set; }
public IEnumerable<SelectListItem> DepartmentList { get; set; }
public int DepartmentID { get; set; }
}
这是我的POST的POST和GET方法 AccountController.cs
// GET: /Account/Register
[AllowAnonymous]
public ActionResult Register()
{
RegisterViewModel model = new RegisterViewModel();
ConfigureRegisterViewModel(model);
return View(model);
}
//
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (!ModelState.IsValid)
{
ConfigureRegisterViewModel(model);
return View(model);
}
var user = new ApplicationUser() {
UserName = model.Email,
Email = model.Email,
FirstMidName = model.FirstMidName,
LastName = model.LastName,
EnrollmentDate = model.EnrollmentDate,
DepotID = model.DepotID,
DepartmentID = model.DepartmentID,
Id = model.Id //My RoleID
};
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
var code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking this link: <a href=\"" + callbackUrl + "\">link</a>");
ViewBag.Link = callbackUrl;
return View("DisplayEmail");
}
AddErrors(result);
// If we got this far, something failed, redisplay form
ConfigureRegisterViewModel(model);
return View(model);
}
private void ConfigureRegisterViewModel(RegisterViewModel model)
{
IEnumerable<Department> departments = db.Departments.OrderBy(u => u.DepartmentName);
model.DepartmentList = departments.Select(a => new SelectListItem
{
Value = a.DepartmentID.ToString(),
Text = a.DepartmentName.ToString()
});
IEnumerable<Depot> depots = db.Depots.OrderBy(u => u.DepotName);
model.DepotList = depots.Select(a => new SelectListItem
{
Value = a.DepotID.ToString(),
Text = a.DepotName.ToString()
});
IEnumerable<RegisterViewModel> roles = db.Roles.OrderBy(u => u.Name); <-- ERROR HERE
model.RolesList = roles.Select(a => new SelectListItem
{
Value = a.Id.ToString(),
Text = a.Name.ToString()
});
}
Register.cshtml
<div class="form-group">
@Html.LabelFor(m => m.Id, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.DropDownListFor(m => m.Id, Model.RolesList, "Please select", new { @class = "form-control" })
</div>
</div>
此代码仅供参考
IdentityModel.cs(ApplicationUser类)
namespace RecreationalServicesTicketingSystem.Models
{
public class ApplicationUserLogin : IdentityUserLogin<int> { }
public class ApplicationUserClaim : IdentityUserClaim<int> { }
public class ApplicationUserRole : IdentityUserRole<int> { }
public class ApplicationRole : IdentityRole<int, ApplicationUserRole>, IRole<int>
{
public string Description { get; set; }
public ApplicationRole() : base() { }
public ApplicationRole(string name)
: this()
{
this.Name = name;
}
public ApplicationRole(string name, string description)
: this(name)
{
this.Description = description;
}
}
public class ApplicationUser : IdentityUser<int, ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>, IUser<int>
{
public async Task<ClaimsIdentity>
GenerateUserIdentityAsync(UserManager<ApplicationUser, int> manager)
{
var userIdentity = await manager
.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
return userIdentity;
}
public bool IsAdministrator { get; set; }
[StringLength(50, MinimumLength = 1)]
public string LastName { get; set; }
[StringLength(50, MinimumLength = 1, ErrorMessage = "First name cannot be longer than 50 characters.")]
[Column("FirstName")]
public string FirstMidName { get; set; }
public string FullName
{
get { return FirstMidName + " " + LastName; }
}
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime EnrollmentDate { get; set; }
public int DepartmentID { get; set; }
[ForeignKey("DepartmentID")]
public virtual Department Department { get; set; }
public int DepotID { get; set; }
[ForeignKey("DepotID")]
public virtual Depot Depot { get; set; }
public virtual ICollection<Ticket> Tickets { get; set; }
//Adding Roles to Register page code start
//RoleID
public int Id { get; set; }
[Required(AllowEmptyStrings = false)]
//RoleName
[Display(Name = "RoleName")]
public string Name { get; set; }
//Adding Roles to Register page code end
}
public class ApplicationDbContext
: IdentityDbContext<ApplicationUser, ApplicationRole, int,
ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>
{
public ApplicationDbContext()
: base("DefaultConnection")
{
}
static ApplicationDbContext()
{
Database.SetInitializer<ApplicationDbContext>(new ApplicationDbInitializer());
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
public DbSet<Ticket> Tickets { get; set; }
public DbSet<Category> Categories { get; set; }
public DbSet<Department> Departments { get; set; }
public DbSet<Depot> Depots { get; set; }
}
public class ApplicationUserStore :
UserStore<ApplicationUser, ApplicationRole, int,
ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>, IUserStore<ApplicationUser, int>, IDisposable
{
public ApplicationUserStore()
: this(new IdentityDbContext())
{
base.DisposeContext = true;
}
public ApplicationUserStore(DbContext context)
: base(context)
{
}
}
public class ApplicationRoleStore
: RoleStore<ApplicationRole, int, ApplicationUserRole>,
IQueryableRoleStore<ApplicationRole, int>,
IRoleStore<ApplicationRole, int>, IDisposable
{
public ApplicationRoleStore()
: base(new IdentityDbContext())
{
base.DisposeContext = true;
}
public ApplicationRoleStore(DbContext context)
: base(context)
{
}
}
}
答案 0 :(得分:1)
您缺少ToList
功能。 IEnumerable
会帮助您将其转换为IEnumerable<RegisterViewModel> roles = db.Roles.OrderBy(u => u.Name).ToList();
。它应该是
{{1}}
答案 1 :(得分:0)
解决方案是
的IEnumerable&LT; ApplicationRole&GT; roles = db.Roles.OrderBy(u =&gt; u.Name)。ToList();