在下拉列表()中显示类型而不是数据



尝试用viewModel填充用户和角色,但它显示了类型而不是诸如system.data.entity.dynamicproxies.appuser.appuser.xxx(for用户)和system.data.data.entity.entity.entity.entity。。

代码如下。

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; }
    }

ViewModel

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时,它可以很好地工作,除了无法实现的theDropDowns(必需验证)的验证,因此在这种情况下,采用带有必需注释的ViewModel和ViewModel是建议的方法。感谢任何帮助。提前致谢 。使用MVC 5,具有身份的CodeFirst EF。

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

在您的视图模型中更改

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

to

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

并将Required属性添加到SelectedIdSelectedRoleId

在您的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()
        });

btw,使用 Select()这样的

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

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

相关内容

  • 没有找到相关文章

最新更新