1

I have just added custom properties to the ApplicationUser class, which has worked and the database is now storing those properties. However, I am not sure how to display these properties on the MVC view.

This is my application user class:

using System;
using Microsoft.AspNetCore.Identity;

namespace IssueTracker.Areas.Identity.Data
{
    public class ApplicationUser : IdentityUser
    {
        public String? FirstName { get; set; }

        public String? LastName { get; set; }

        public int? RoleNumber { get; set; }

    }
}

Originally, my _LoginPartial.cshtml references the Identity name through this line:

@User.Identity?.Name

How can I change this to show the FirstName property? Additionally, how can I change this so that I can access all 3 properties from the ApplicationUser class on any view or partial view?

I have tried looking at other posts, but most are outdated and did not work. Thank you! I am new to MVC, so forgive me if my question is simple or if I come across as a starter.

1 Answer 1

1

You can inject UserManager<T> into your view, Then get the value. refer to this simple demo:

@inject  UserManager<ApplicationUser> userManager;


<h2>
@foreach (var item in userManager.Users)
  {
     //Then you can get the value of these proerties.
      @item.FirstName
      @items.LastName 
      @items.RoleNumber
      
  }
</h2>

Mode details you can refer to Dependency injection into views in ASP.NET Core.

If you want to show the properties of the currently logged in user, You can refer to this demo:

Add Httpcontext in program.cs:

builder.Services.AddHttpContextAccessor();

In View:

@using Microsoft.AspNetCore.Http;

@inject  UserManager<AppUser> userManager;
@inject IHttpContextAccessor _context;

@{
   var user =await userManager.GetUserAsync(_context.HttpContext.User);
}

   

  <h1>
      @user.FirstName 
      @user.LastName
      //......
  </h1>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.