View and Edit Profile Details in ASP.NET Core Identity

How to View and Edit Profile Details in ASP.NET Core Identity

In this article, I will discuss How to View and Edit Profile Details in ASP.NET Core Identity with an Example. Please read our previous article discussing How to Implement CAPTCHA in ASP.NET Core Identity.

View and Edit Profile Details in ASP.NET Core Identity

Viewing and updating user profiles are essential functionalities in any web application that manages user accounts. In ASP.NET Core Identity, managing user profile details involves two key operations:

  • View Profile: To allow users to see their current profile details. It provides an overview of account-related information such as name, email, phone number, email confirmation status, phone confirmation status, two-factor authentication (2FA) status, and more.
  • Edit Profile: Allows users to update their profile details, such as first name, last name, or phone number. Ensures that specific fields, like email, remain secure and can only be updated with additional verification steps.
Implementing View and Edit Profile in ASP.NET Core Identity:

Before Implementing, let us first understand the workflow. So, when the user is logged in, we need to provide two links within the My Account dropdown list to see the Profile details and update the profile details as shown in the image below:

Implementing View and Edit Profile in ASP.NET Core Identity

My Profile Link:

When the user clicks on the My Profile link, it will open the following page displaying the profile details:

View and Edit Profile Details in ASP.NET Core Identity

View Profile is the functionality that allows an authenticated user to see their personal details (e.g., name, email, phone number, two-factor authentication status, etc.) stored in the Identity database. This page often displays important security or account verification information, such as whether the user’s email or phone number is confirmed.

Update Profile Link:

When the user clicks on the Update Profile link, it will open the following page, allowing the user to update the profile details:

How to View and Edit Profile Details in ASP.NET Core Identity

Update Profile is the feature that lets users change certain pieces of their information, like their first name, last name, or phone number, while preventing changes to more sensitive fields (like email, which often requires additional security measures). Let us proceed and see how to implement this step by step in our application.

MyProfile Action Method:

Please add the following action method to the Account Controller. This GET action method retrieves the current user’s profile information and renders the MyProfile view.

[HttpGet]
[Authorize]
public async Task<IActionResult> MyProfile()
{
    var user = await userManager.GetUserAsync(User);
    if (user == null)
    {
        return RedirectToAction("Login", "Account");
    }

    return View(user);
}
My Profile View:

Next, add the following MyProfile.cshtml view within the Views/Account folder and copy and paste the following code. This view Displays the current user’s profile information, such as name, email, phone number, email confirmation status, phone confirmation status, 2FA status, and the date of the last password change.

@model ASPNETCoreIdentityDemo.Models.ApplicationUser
@{
    ViewData["Title"] = "My Profile";
}

<div class="container mt-5">
    <!-- Page Header -->
    <div class="row justify-content-center">
        <div class="col-md-8 text-center">
            <h1 class="fw-bold text-primary">Account Overview</h1>
            <p class="text-muted fs-6">
                Please review your account information below. If you need
                to update any details, simply click the&nbsp;
                <strong>Edit Profile</strong> button or contact our support team
                for assistance. We appreciate your help in keeping this
                information accurate.
            </p>
        </div>

        @if (TempData["ProfileUpdateSuccess"] != null)
        {
            <div class="col-md-8 text-center">
                <p class="text-primary">
                    @TempData["ProfileUpdateSuccess"]
                </p>
            </div>
        }
    </div>

    <!-- Profile Section -->
    <div class="row justify-content-center">
        <div class="col-md-12 col-lg-10">
            <div class="card shadow-lg border-0 rounded-3">
                <!-- Card Header -->
                <div class="card-header bg-primary text-white text-center py-4 rounded-top">
                    <h3 class="mb-0">Account Information</h3>
                </div>

                <!-- Card Body -->
                <div class="card-body p-4">
                    <div class="row">
                        <!-- Profile Picture Placeholder -->
                        <div class="col-md-3 text-center">
                            <img src="https://picsum.photos/150" alt="Profile Picture" class="rounded-circle mb-3 shadow" />
                            <h5 class="text-primary fw-bold">@Model.FirstName @Model.LastName</h5>
                        </div>

                        <!-- User Details -->
                        <div class="col-md-9">
                            <table class="table table-borderless">
                                <tbody>
                                    <tr>
                                        <th class="text-end text-muted col-md-4">Email:</th>
                                        <td class="col-md-8">@Model.Email</td>
                                    </tr>
                                    <tr>
                                        <th class="text-end text-muted col-md-4">Email Confirmed:</th>
                                        <td class="col-md-8">
                                            @if (Model.EmailConfirmed)
                                            {
                                                <span class="badge bg-success">Yes</span>
                                            }
                                            else
                                            {
                                                <a asp-action="ResendConfirmationEmail" asp-controller="Account" class="btn btn-sm btn-danger">Verify Email</a>
                                            }
                                        </td>
                                    </tr>
                                    <tr>
                                        <th class="text-end text-muted col-md-4">Phone Number:</th>
                                        <td class="col-md-8">@(Model.PhoneNumber ?? "Not Provided")</td>
                                    </tr>
                                    <tr>
                                        <th class="text-end text-muted col-md-4">Phone Confirmed:</th>
                                        <td class="col-md-8">
                                            @if (Model.PhoneNumberConfirmed)
                                            {
                                                <span class="badge bg-success">Yes</span>
                                            }
                                            else
                                            {
                                                <a asp-action="ConfirmPhoneNumber" asp-controller="Account" class="btn btn-sm btn-danger">Verify Phone</a>
                                            }
                                        </td>
                                    </tr>
                                    <tr>
                                        <th class="text-end text-muted col-md-4">2FA Enabled:</th>
                                        <td class="col-md-8">
                                            <span class="px-3 py-1 fw-bold text-white rounded-pill"
                                                  style="display: inline-block; background-color: @(Model.TwoFactorEnabled ? "#28a745" : "#dc3545");">
                                                @(Model.TwoFactorEnabled ? "Enabled" : "Disabled")
                                            </span>
                                            @if (!Model.TwoFactorEnabled)
                                            {
                                                <p class="text-danger mt-2">
                                                    Enhance your security by enabling Two-Factor Authentication.
                                                    <a asp-action="ManageTwoFactorAuthentication" asp-controller="Account" class="text-primary fw-bold">Enable Now</a>
                                                </p>
                                            }
                                        </td>
                                    </tr>
                                    <tr>
                                        <th class="text-end text-muted col-md-4">Last Password Change:</th>
                                        <td class="col-md-8">@Model.LastPasswordChangedDate.ToString("f")</td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>

                <!-- Card Footer -->
                <div class="card-footer bg-light text-end py-3">
                    <a asp-action="EditProfile" asp-controller="Account" class="btn btn-warning me-2">Edit Profile</a>
                    <a asp-action="ChangePassword" asp-controller="Account" class="btn btn-primary">Change Password</a>
                </div>
            </div>
        </div>
    </div>
</div>
Edit Profile View Model

Next, we need to create a View Model to edit a user’s profile details. So, add a class file named EditProfileViewModel.cs within the Models folder and then copy and paste the following code. This model acts as a data transfer object (DTO) for editing the user’s profile.

using System.ComponentModel.DataAnnotations;
namespace ASPNETCoreIdentityDemo.Models
{
    public class EditProfileViewModel
    {
        [Required(ErrorMessage = "First Name is required.")]
        [Display(Name = "First Name")]
        [StringLength(50, ErrorMessage = "First Name cannot exceed 50 characters.")]
        public string? FirstName { get; set; }

        [Required(ErrorMessage = "Last Name is required.")]
        [Display(Name = "Last Name")]
        [StringLength(50, ErrorMessage = "Last Name cannot exceed 50 characters.")]
        public string? LastName { get; set; }

        [Display(Name = "Phone Number")]
        [Phone(ErrorMessage = "Please enter a valid phone number.")]
        public string? PhoneNumber { get; set; }

        [Display(Name = "Email Address")]
        public string? Email { get; set; } // Email is not editable
    }
}
EditProfile Get Action Method:

Next, add the following EditProfile GET action method into the Account Controller. This GET action method fetches the current user’s details and prepares a view model for editing their profile.

[HttpGet]
[Authorize]
public async Task<IActionResult> EditProfile()
{
    var user = await userManager.GetUserAsync(User);
    if (user == null)
    {
        return RedirectToAction("Login", "Account");
    }

    // Prepare the model for editing
    var model = new EditProfileViewModel
    {
        FirstName = user.FirstName,
        LastName = user.LastName,
        PhoneNumber = user.PhoneNumber,
        Email = user.Email
    };

    return View(model);
}
EditProfile Post Action Method:

Next, add the following EditProfile POST action method into the Account Controller. This action method Handles the form submission when the user updates their profile.

[HttpPost]
[Authorize]
public async Task<IActionResult> EditProfile(EditProfileViewModel model)
{
    if (!ModelState.IsValid)
    {
        return View(model); // Return the view with validation errors
    }

    var user = await userManager.GetUserAsync(User);
    if (user == null)
    {
        return RedirectToAction("Login", "Account");
    }

    // Update the user's profile details
    user.FirstName = model.FirstName;
    user.LastName = model.LastName;

    // Check if the phone number has changed
    if (user.PhoneNumber != model.PhoneNumber)
    {
        user.PhoneNumber = model.PhoneNumber;
        user.PhoneNumberConfirmed = false; // Mark as not confirmed
    }

    var result = await userManager.UpdateAsync(user);
    if (result.Succeeded)
    {
        // Re-sign user in if security stamp changes
        await signInManager.RefreshSignInAsync(user);

        TempData["ProfileUpdateSuccess"] = "Your profile has been updated successfully.";
        return RedirectToAction("MyProfile"); // Redirect to the User Details page
    }
    else
    {
        // If update fails, add errors to ModelState
        foreach (var error in result.Errors)
        {
            ModelState.AddModelError(string.Empty, error.Description);
        }
        return View(model);
    }
}
EditProfile View:

Next, add a view named EditProfile.cshtml within the Views/Account folder and copy and paste the following code. This view provides a form for users to edit their profile information (First Name, Last Name, and Phone Number).

@model ASPNETCoreIdentityDemo.Models.EditProfileViewModel

@{
    ViewData["Title"] = "Edit Profile";
}

<div class="container mt-5">
    <div class="row justify-content-center">
        <div class="col-md-10 col-lg-8">
            <!-- Page Header -->
            <div class="text-center mb-2">
                <h1 class="fw-bold text-primary">Manage Your Profile</h1>
                <p class="text-muted fs-5">
                    Ensure your profile details are accurate to keep your account secure. For security purposes, email changes require assistance from our support team.
                </p>
            </div>

            <!-- Card for Form -->
            <div class="card shadow-lg border-0 rounded-4">
                <div class="card-header bg-primary text-white text-center rounded-top">
                    <h3 class="mb-0">Update Your Profile Information</h3>
                </div>
                <div class="card-body p-4">
                    <form asp-action="EditProfile" asp-controller="Account" method="post" novalidate>
                        @Html.AntiForgeryToken()

                        <!-- First Name -->
                        <div class="row mb-4">
                            <label asp-for="FirstName" class="col-md-4 col-form-label text-end fw-bold text-muted"></label>
                            <div class="col-md-8">
                                <input asp-for="FirstName" class="form-control shadow-sm" placeholder="Enter your first name" />
                                <span asp-validation-for="FirstName" class="text-danger small"></span>
                            </div>
                        </div>

                        <!-- Last Name -->
                        <div class="row mb-4">
                            <label asp-for="LastName" class="col-md-4 col-form-label text-end fw-bold text-muted"></label>
                            <div class="col-md-8">
                                <input asp-for="LastName" class="form-control shadow-sm" placeholder="Enter your last name" />
                                <span asp-validation-for="LastName" class="text-danger small"></span>
                            </div>
                        </div>

                        <!-- Email -->
                        <div class="row mb-4">
                            <label asp-for="Email" class="col-md-4 col-form-label text-end fw-bold text-muted"></label>
                            <div class="col-md-8">
                                <input asp-for="Email" class="form-control shadow-sm bg-light" readonly />
                                <small class="form-text text-muted">
                                    Your email address is locked and cannot be changed directly. Please contact our support team for email updates.
                                </small>
                            </div>
                        </div>

                        <!-- Phone Number -->
                        <div class="row mb-4">
                            <label asp-for="PhoneNumber" class="col-md-4 col-form-label text-end fw-bold text-muted"></label>
                            <div class="col-md-8">
                                <input asp-for="PhoneNumber" class="form-control shadow-sm" placeholder="Enter your phone number" />
                                <small class="form-text text-muted">
                                    If you update your phone number, you will need to verify it again for security purposes.
                                </small>
                                <span asp-validation-for="PhoneNumber" class="text-danger small"></span>
                            </div>
                        </div>

                        <!-- Validation Summary -->
                        <div asp-validation-summary="All" class="text-danger small mb-4 text-center"></div>

                        <!-- Buttons -->
                        <div class="row">
                            <div class="col-md-4"></div>
                            <div class="col-md-8 text-end">
                                <button type="submit" class="btn btn-primary px-4 me-2">
                                    Save Changes
                                </button>
                                <a asp-action="MyProfile" asp-controller="Account" class="btn btn-danger px-4">
                                    Cancel
                                </a>
                            </div>
                        </div>
                    </form>
                </div>
                <!-- Card Footer -->
                <div class="card-footer bg-light text-center" style="border-radius: 0 0 0.5rem 0.5rem;">
                    <small class="text-muted">
                        Regularly updating your profile helps us provide personalized services and ensures your account's security.
                    </small>
                </div>
            </div>
        </div>
    </div>
</div>
Modifying Layout View:

Adds navigation links to the My Profile and Update Profile pages within the “My Account” dropdown menu in the shared layout. So, please add the following code with _Layout.cshtml file, and you need to add these codes just before the code, which renders the Sign Out link within the My Account dropdown list.

<li>
    <a class="dropdown-item" asp-controller="Account"
       asp-action="MyProfile">My Profile</a>
</li>
<li>
    <a class="dropdown-item" asp-controller="Account"
       asp-action="EditProfile">Update Profile</a>
</li>

By implementing View Profile and Update Profile in ASP.NET Core Identity, you ensure that users can understand and manage their own information in a secure and user-friendly manner.

In the next article, I will discuss ASP.NET Core Identity Interview Questions and Answers. In this article, I explain How to View and Edit Profile Details in ASP.NET Core Identity. I hope you enjoy this article on How to View and Edit Profile Details in ASP.NET Core Identity.

Registration Open For New Online Training

Enhance Your Professional Journey with Our Upcoming Live Session. For complete information on Registration, Course Details, Syllabus, and to get the Zoom Credentials to attend the free live Demo Sessions, please click on the below links.

Leave a Reply

Your email address will not be published. Required fields are marked *