【问题标题】:How to edit user profile such as user role in Asp.Net Mvc?如何在 Asp.Net Mvc 中编辑用户配置文件,例如用户角色?
【发布时间】:2018-05-06 13:49:44
【问题描述】:

我想在我的 _EditUser 视图中显示用户配置文件,然后编辑用户配置文件,例如用户角色..姓名和电子邮件。

但是当涉及到用户角色时,它就崩溃了。我得到 500(内部服务器错误) 它在这里崩溃了:

model.ApplicationRoleId = RoleManager.Roles.Single(r => r.Name == UserManager.GetRoles(id).Single()).Id;

这是我的 EditUserview

    public class EditUserViewModel
    {
      public string Id { get; set; }
      public string Name { get; set; }
      public string Email { get; set; }
      public List<SelectListItem> ApplicationRoles { get; set; }
      public string ApplicationRoleId { get; set; }
    }

这是我的 EditUser 操作

[HttpGet]
public async Task<IActionResult> EditUser(string id)
{
    EditUserViewModel model = new EditUserViewModel();
    model.ApplicationRoles = roleManager.Roles.Select(r => new SelectListItem
    {
        Text = r.Name,
        Value = r.Id
    }).ToList();



    if (!String.IsNullOrEmpty(id))
    {
        ApplicationUser user = await userManager.FindByIdAsync(id);
        if (user != null)
        {
          model.Name = user.Name;
          model.Email = user.Email;
          model.ApplicationRoleId = RoleManager.Roles.Single(r => r.Name == UserManager.GetRoles(id).Single()).Id; // Here crashing .. I don't know why.. Server 500 error
          ViewBag.RoleId = new SelectList(RoleManager.Roles, "Id", "Name", model.ApplicationRoleId);
         }
    }
    return PartialView("_EditUser", model);
}

在我的视图页面“_EditUser.cshtml”中,我的用户角色下拉列表如下所示

<div class="form-group">
                @Html.Label("Role", htmlAttributes: new { @class = "control-label col-md-6" })
                <div class="col-md-12" >
                    @Html.DropDownList("RoleId", null, htmlAttributes: new { @class = "form-control" })
                    @Html.ValidationMessageFor(model => model.ApplicationRoles, "", new { @class = "text-danger" })
                </div>
            </div>

/提前谢谢你

【问题讨论】:

  • Single 方法将在集合(您在其上调用该方法)为空或返回多个匹配条件的元素时抛出异常。
  • @Shyju 你能否给我更多的解决方案答案,b/c 这是我第二次问。我有足够的散乱,但无法解决。
  • 请贴出超过500的错误(内部服务器错误)
  • @DaniDev GET ....Account/EditUser?id=683c1264-075f-4d51-9346-b9349fb23bea 500(内部服务器错误)jquery-3.1.1.js:9536
  • 1.如果您知道您的应用程序在上述行“崩溃”,那么您可以在此处设置一个断点。并且您应该能够获得有关导致错误的原因的详细消息。 2. 使用 SingleOrDefault() 而不是 Single() ?

标签: asp.net asp.net-mvc user-roles


【解决方案1】:

正如@Shyju 在我的旧问题中所写的那样,我确实喜欢这样做

var role = await UserManager.GetRolesAsync(user.Id);
                    var existingRole = role.First();
 if (existingRole != null)
  {
 string existingRoleId = RoleManager.Roles.Single(r => r.Name == existingRole).Id;
model.ApplicationRoleId = existingRoleId;
.....  and so on ....

}

谢谢你们和@Shyju

【讨论】:

    猜你喜欢
    • 2018-03-26
    • 1970-01-01
    • 1970-01-01
    • 2010-11-20
    • 1970-01-01
    • 2020-10-16
    • 1970-01-01
    • 1970-01-01
    • 2017-12-24
    相关资源
    最近更新 更多