Support us .Net Basics C# SQL ASP.NET Aarvi MVC Slides C# Programs Subscribe Download

Edit identity user in asp.net core

Suggested Videos
Part 82 - ASP.NET Core role based authorization | Text | Slides
Part 83 - Show or hide navigation menu based on user role in asp.net core | Text | Slides
Part 84 - List all users from asp.net core identity database | Text | Slides

In this video we will discuss how to edit identity user in asp.net core


Edit button on List Users View

When we click on the Edit button against any employee on the ListUsers view, we want to redirect the user to /Administration/EditUser/UserId.


edit identity user in asp.net core

<div class="card-footer">
    <a asp-action="EditUser" asp-controller="Administration"
        asp-route-id="@user.Id" class="btn btn-primary">Edit</a>
    <a href="#" class="btn btn-danger">Delete</a>
</div>

Edit Identity User View

The look and feel of EditUser view is shown below.

asp.net core identity edit user

Edit User View Model 

The following is the EditUserViewModel class that carries the data the view needs.

public class EditUserViewModel
{
    public EditUserViewModel()
    {
        Claims = new List<string>();
        Roles = new List<string>();
    }

    public string Id { get; set; }

    [Required]
    public string UserName { get; set; }

    [Required]
    [EmailAddress]
    public string Email { get; set; }

    public string City { get; set; }

    public List<string> Claims { get; set; }

    public IList<string> Roles { get; set; }
}

To avoid NullReferenceExceptions at runtime, initialise Claims and Roles with a new list in the constructor.

EditUser HttpGet Action

[HttpGet]
public async Task<IActionResult> EditUser(string id)
{
    var user = await userManager.FindByIdAsync(id);

    if (user == null)
    {
        ViewBag.ErrorMessage = $"User with Id = {id} cannot be found";
        return View("NotFound");
    }

    // GetClaimsAsync retunrs the list of user Claims
    var userClaims = await userManager.GetClaimsAsync(user);
    // GetRolesAsync returns the list of user Roles
    var userRoles = await userManager.GetRolesAsync(user);

    var model = new EditUserViewModel
    {
        Id = user.Id,
        Email = user.Email,
        UserName = user.UserName,
        City = user.City,
        Claims = userClaims.Select(c => c.Value).ToList(),
        Roles = userRoles
    };

    return View(model);
}

EditUser HttpPost Action

[HttpPost]
public async Task<IActionResult> EditUser(EditUserViewModel model)
{
    var user = await userManager.FindByIdAsync(model.Id);

    if (user == null)
    {
        ViewBag.ErrorMessage = $"User with Id = {model.Id} cannot be found";
        return View("NotFound");
    }
    else
    {
        user.Email = model.Email;
        user.UserName = model.UserName;
        user.City = model.City;

        var result = await userManager.UpdateAsync(user);

        if (result.Succeeded)
        {
            return RedirectToAction("ListUsers");
        }

        foreach (var error in result.Errors)
        {
            ModelState.AddModelError("", error.Description);
        }

        return View(model);
    }
}

EditUser View

@model EditUserViewModel

@{
    ViewBag.Title = "Edit User";
}

<h1>Edit User</h1>

<form method="post" class="mt-3">
    <div class="form-group row">
        <label asp-for="Id" class="col-sm-2 col-form-label"></label>
        <div class="col-sm-10">
            <input asp-for="Id" disabled class="form-control">
        </div>
    </div>
    <div class="form-group row">
        <label asp-for="Email" class="col-sm-2 col-form-label"></label>
        <div class="col-sm-10">
            <input asp-for="Email" class="form-control">
            <span asp-validation-for="Email" class="text-danger"></span>
        </div>
    </div>
    <div class="form-group row">
        <label asp-for="UserName" class="col-sm-2 col-form-label"></label>
        <div class="col-sm-10">
            <input asp-for="UserName" class="form-control">
            <span asp-validation-for="UserName" class="text-danger"></span>
        </div>
    </div>
    <div class="form-group row">
        <label asp-for="City" class="col-sm-2 col-form-label"></label>
        <div class="col-sm-10">
            <input asp-for="City" class="form-control">
        </div>
    </div>

    <div asp-validation-summary="All" class="text-danger"></div>

    <div class="form-group row">
        <div class="col-sm-10">
            <button type="submit" class="btn btn-primary">Update</button>
            <a asp-action="ListUsers" class="btn btn-primary">Cancel</a>
        </div>
    </div>

    <div class="card">
        <div class="card-header">
            <h3>User Roles</h3>
        </div>
        <div class="card-body">
            @if (Model.Roles.Any())
            {
                foreach (var role in Model.Roles)
                {
                    <h5 class="card-title">@role</h5>
                }
            }
            else
            {
                <h5 class="card-title">None at the moment</h5>
            }
        </div>
        <div class="card-footer">
            <a href="#" style="width:auto" class="btn btn-primary">
                Manage Roles
            </a>
        </div>
    </div>

    <div class="card mt-3">
        <div class="card-header">
            <h3>User Claims</h3>
        </div>
        <div class="card-body">
            @if (Model.Claims.Any())
            {
                foreach (var claim in Model.Claims)
                {
                    <h5 class="card-title">@claim</h5>
                }
            }
            else
            {
                <h5 class="card-title">None at the moment</h5>
            }
        </div>
        <div class="card-footer">
            <a href="#" style="width:auto" class="btn btn-primary">
                Manage Claims
            </a>
        </div>
    </div>
</form>

asp.net core tutorial for beginners

No comments:

Post a Comment

It would be great if you can help share these free resources