Home > OS >  user.FirstName in .cshtml.cs file is null
user.FirstName in .cshtml.cs file is null

Time:08-29

I'm using Identity in my .net core 6 mvc app and I'm trying to display the users first name in a razor page, here's the .cshtml.cs file:

using CubeAuthAttempt1.Areas.Identity.Data;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace CubeAuthAttempt1.Areas.Identity.Pages.Account.Manage
{
    public class WorkModel : PageModel
    {

        private readonly UserManager<ApplicationUser> _userManager;

        //constructor 
        public WorkModel(UserManager<ApplicationUser> userManager)
        {
            _userManager = userManager;
        }

        public void OnGet(ApplicationUser user)
        {
            ViewData["firstname"] = user.FirstName; 
        }
    }
}

.cshtml file:

@page
@model CubeAuthAttempt1.Areas.Identity.Pages.Account.Manage.WorkModel
@{
}


<div>
    <h2>Hello @ViewData["firstname"]</h2>
</div>

ApplicationUser.cs:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using CubeAuthAttempt1.Models;
using Microsoft.AspNetCore.Identity;

namespace CubeAuthAttempt1.Areas.Identity.Data;

// Add profile data for application users by adding properties to the ApplicationUser class
public class ApplicationUser : IdentityUser
{
    [Required]
    public string FirstName { get; set; }

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

    public string Address { get; set; }

    public List<Cart> Cart { get; set; }
}

When I debugged this to see what the value of user.FirstName is I got this:

enter image description here

Thank you in advance, much appreciated.

CodePudding user response:

Parameters of OnGet method are used to pass values from the url. For example:

public class WorkModel : PageModel
{
    public void OnGet(int? id)
    {
    }
}

You need to go to this url to pass the id parameter the value 123

http://localhost:{port}/Work?id=123

If you navigate to "http://localhost:{port}/Work" id parameter will be null.

So trying to pass the ApplicationUser as an OnGet parameter is wrong and it's null because we are not passing any query string parameters when requesting the Work page.

This is how you should do it:

public void OnGet()
{
    // holds identity information of the user who made the request, known as 'claims'
    var principal = User;

    // retrieve the ApplicationUser using UserManager
    var user = await _userManager.GetUserAsync(principal);
    
    ViewData["firstname"] = user.FirstName; 
}
  • Related