在DropDownListFor()

时间:2017-09-05 15:38:27

标签: asp.net-mvc entity-framework asp.net-identity viewmodel

尝试使用ViewModel填充用户和角色,但它显示的是类型而不是System.Data.Entity.DynamicProxies.AppUser.xxx(对于用户)和System.Data.Entity.DynamicProxies.IdentityRole.xxx(对于角色)。

代码如下。

public class AppUser : IdentityUser
    {
        //add custom properties which have not included in IdentityUser before
        public string Designation { get; set; }

        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<AppUser> manager)
        {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType 
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            // Add custom user claims here 
            return userIdentity;
        }

        public static ERPContext Create()
        {
            return new ERPContext();
        }
    } 



public class AppRole : IdentityRole
    {
        public AppRole() : base() { }
        public AppRole(string name) : base(name) { }
        // extra properties here 
        public string Description { get; set; }
    }

视图模型

public class UserAssignRoleViewModel
    {

        public string Username { get; set; }

        public string Role { get; set; }
        [Required]
        public List<AppUser> Users { get; set; }
        [Required]
        public List<IdentityRole> Roles { get; set; }

        public int SelectedId { set; get; }

        public int SelectedRoleId { set; get; }
    }

RoleController

  public ActionResult ManageUserRoles()
        {
            //this code is also an alternate way to fetch the roles from Owin // Startup config
            // var roles = HttpContext.GetOwinContext().GetUserManager<RoleManager<IdentityRole>>().Roles;
            //var rolelist = context.Roles.OrderBy(r => r.Name).ToList().Select(rr => new SelectListItem { Value = rr.Name.ToString(), Text = rr.Name }).ToList();
            var model = new UserAssignRoleViewModel();
            var users = context.Users.ToList();
            users.Select(s => new SelectListItem
            {
                Value = s.Id.ToString(),
                Text = s.UserName.ToString()
            });
            var roles = context.Roles.ToList();
            roles.Select(s => new SelectListItem
            {
                Value = s.Id.ToString(),
                Text = s.Name.ToString()
            });
            ViewBag.Users = users;
            //var list = context.Roles.OrderBy(r => r.Name).ToList().Select(rr => new SelectListItem { Value = rr.Name.ToString(), Text = rr.Name }).ToList();
            //ViewBag.Roles = list;
            model.Users = users;
            model.Roles = roles;
            return View(model);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult RoleAddToUser(string UserName, string RoleName)
        {
            AppUser user = context.Users.Where(u => u.UserName.Equals(UserName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
            var userManager = new UserManager<AppUser>(new UserStore<AppUser>(context));

            userManager.AddToRole(user.Id, RoleName);

            ViewBag.ResultMessage = "Role Assigned successfully !";

            // prepopulat users for the view dropdown
            var _users = context.Users.OrderBy(r => r.UserName).ToList().Select(rr => new SelectListItem { Value = rr.UserName.ToString(), Text = rr.UserName }).ToList();
            ViewBag.Users = _users;
            // prepopulat roles for the view dropdown
            var _roles = context.Roles.OrderBy(r => r.Name).ToList().Select(rr => new SelectListItem { Value = rr.Name.ToString(), Text = rr.Name }).ToList();
            ViewBag.Roles = _roles;

            return View("ManageUserRoles");
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult GetRoles(string UserName)
        {
            if (!string.IsNullOrWhiteSpace(UserName))
            {
                AppUser user = context.Users.Where(u => u.UserName.Equals(UserName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
                var userManager = new UserManager<AppUser>(new UserStore<AppUser>(context));

                ViewBag.RolesForThisUser = userManager.GetRoles(user.Id);


                // prepopulat roles for the view dropdown
                var list = context.Roles.OrderBy(r => r.Name).ToList().Select(rr => new SelectListItem { Value = rr.Name.ToString(), Text = rr.Name }).ToList();
                ViewBag.Roles = list;
                // prepopulat roles for the view dropdown
                var users = context.Users.OrderBy(r => r.UserName).ToList().Select(rr => new SelectListItem { Value = rr.UserName.ToString(), Text = rr.UserName }).ToList();
                ViewBag.Users = users;
            }

            return View("ManageUserRoles");
        }

上面的代码几乎没有我之前尝试过的评论代码。

最后,视图如下

@model ERPLite.Models.UserAssignRoleViewModel
@{
    ViewBag.Title = "ManageUserRoles";

}

@Html.ActionLink("Create New Role", "Create") | @Html.ActionLink("Manage User Role", "ManageUserRoles")
<hr />


@using (Html.BeginForm("RoleAddToUser", "Role"))
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)


    <p>

        User Name: @Html.DropDownListFor(x => x.SelectedId, new SelectList(Model.Users), "Select")
        @*Role Name: @Html.DropDownList("RoleName", (IEnumerable<SelectListItem>)ViewBag.Roles, "Select ...")*@
        Role Name: @Html.DropDownListFor(u => u.SelectedRoleId, new SelectList(Model.Roles), "Select ...")
    </p>

    <input type="submit" value="Save" />
}
<hr />
<h3>Get Roles for a User</h3>
@using (Html.BeginForm("GetRoles", "Role"))
{
    @Html.AntiForgeryToken()
    <p>
        Username : @Html.TextBox("UserName")
        <input type="submit" value="Get Roles for this User" />
    </p>
}

@if (ViewBag.RolesForThisUser != null)
{
    <div style="background-color:yellow;">
        <h3>Roles for this user </h3>
        <ol>
            @foreach (string s in ViewBag.RolesForThisUser)
            {
                <li>@s</li>
            }
        </ol>
    </div>
}

虽然我使用的是ViewBag但它的工作原理完全正常,但是对于下游的验证(必需的验证)无法实现,因此在这种情况下采用带有Required Annotation和ViewModel的ViewModel是推荐的方法。 感谢任何帮助。提前致谢 。 使用MVC 5,CodeFirst EF with Identity。

1 个答案:

答案 0 :(得分:2)

您在视图模型中使用的是身份模型,而不是SelectListItem

在您的视图中更改模型

    [Required]
    public List<AppUser> Users { get; set; }
    [Required]
    public List<IdentityRole> Roles { get; set; }

    public List<SelectListItem> Users { get; set; }
    public List<SelectListItem> Roles { get; set; }

并向RequiredSelectedId添加SelectedRoleId属性。

ManageUserRoles操作中,将视图模型的填充更改为

        model.Users = users.Select(s => new SelectListItem
        {
            Value = s.Id.ToString(),
            Text = s.UserName.ToString()
        });
        var roles = context.Roles.ToList();
        model.Roles = roles.Select(s => new SelectListItem
        {
            Value = s.Id.ToString(),
            Text = s.Name.ToString()
        });

顺便说一句,使用Select()这样的

var roles = context.Roles.ToList();
        roles.Select(s => new SelectListItem
        {
            Value = s.Id.ToString(),
            Text = s.Name.ToString()
        });

什么都不做。您必须将Select的结果分配给变量。