Search code examples
c#asp.net-core-identity

Adding name to the user model in Asp.Net Core Identity


I am trying to add the functionality to edit a user's name in Identity, manage account.

This is my ApplicationUser-model:

public class ApplicationUser : IdentityUser
{
    [Required]
    public string FirstName { get; set; }
    [Required]
    public string LastName { get; set; }
}

This is the default, scaffolded code for updating the profile information (currently, only phone number) (in /Areas/Identity/Pages/Account/Manage/index.cshtml.cs):

public async Task<IActionResult> OnPostAsync()
{
    var user = await _userManager.GetUserAsync(User);
    if (user == null)
    {
        return NotFound($"Could not find user ID '{_userManager.GetUserId(User)}'.");
    }

    if (!ModelState.IsValid)
    {
        await LoadAsync(user);
        return Page();
    }

    var phoneNumber = await _userManager.GetPhoneNumberAsync(user);
    if (Input.PhoneNumber != phoneNumber)
    {
        var setPhoneResult = await _userManager.SetPhoneNumberAsync(user, Input.PhoneNumber);
        if (!setPhoneResult.Succeeded)
        {
            var userId = await _userManager.GetUserIdAsync(user);
            throw new InvalidOperationException($"An error occured while registering the phone number for user ID '{userId}'.");
        }
    }

    await _signInManager.RefreshSignInAsync(user);
    StatusMessage = "Your profile was updated";
    return RedirectToPage();
}

I have added FirstName and LastName in the appropriate places:

The input model (code-behind):

public class InputModel
{
    [Display(Name = "First name")]
    public string FirstName { get; set; }

    [Display(Name = "Last name")]
    public string LastName { get; set; }

    [Phone]
    [Display(Name = "Phone number")]
    public string PhoneNumber { get; set; }
}

The input form:

<form id="profile-form" method="post">
    <div asp-validation-summary="All" class="text-danger"></div>
    <div class="form-group">
        <label asp-for="Username"></label>
        <input asp-for="Username" class="form-control" disabled />
    </div>
    <div class="form-group">
        <label asp-for="Input.FirstName"></label>
        <input asp-for="Input.FirstName" class="form-control" />
        <span asp-validation-for="Input.FirstName" class="text-danger"></span>
    </div>
    <div class="form-group">
        <label asp-for="Input.LastName"></label>
        <input asp-for="Input.LastName" class="form-control" />
        <span asp-validation-for="Input.LastName" class="text-danger"></span>
    </div>
    <div class="form-group">
        <label asp-for="Input.PhoneNumber"></label>
        <input asp-for="Input.PhoneNumber" class="form-control" />
        <span asp-validation-for="Input.PhoneNumber" class="text-danger"></span>
    </div>
    <button id="update-profile-button" type="submit" class="btn btn-primary">
        <span class="fas fa-save"></span>
        Lagre
    </button>
</form>

How would I go about to add the ability to change FirstName and LastName in the same operation?


Solution

  • You should update LoadAsync method for loading/showing the properties :

    private async Task LoadAsync(ApplicationUser user)
    {
        var userName = await _userManager.GetUserNameAsync(user);
        var phoneNumber = await _userManager.GetPhoneNumberAsync(user);
    
        Username = userName;
    
        Input = new InputModel
        {
            PhoneNumber = phoneNumber,            
            FirstName = user.FirstName,
            LastName = user.LastName
        };
    }
    

    And update OnPostAsync method to update FirstName and LastName properties:

    public async Task<IActionResult> OnPostAsync()
    {
        var user = await _userManager.GetUserAsync(User);
        if (user == null)
        {
            return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
        }
    
        if (!ModelState.IsValid)
        {
            await LoadAsync(user);
            return Page();
        }
    
        var phoneNumber = await _userManager.GetPhoneNumberAsync(user);
        if (Input.PhoneNumber != phoneNumber)
        {
            var setPhoneResult = await _userManager.SetPhoneNumberAsync(user, Input.PhoneNumber);
            if (!setPhoneResult.Succeeded)
            {
                var userId = await _userManager.GetUserIdAsync(user);
                throw new InvalidOperationException($"Unexpected error occurred setting phone number for user with ID '{userId}'.");
            }
        }
        if (Input.FirstName != user.FirstName)
        {
            user.FirstName = Input.FirstName;
        }
    
        if (Input.LastName != user.LastName)
        {
            user.LastName = Input.LastName;
        }
    
        await _userManager.UpdateAsync(user);
        await _signInManager.RefreshSignInAsync(user);
        StatusMessage = "Your profile has been updated";
        return RedirectToPage();
    }
    

    Also don't forget to run Add-Migration and Update-Database to update database to include the new columns .