When I login into the application then I stored my UserName in the session, But I can't access it on my partial page. I'm trying to show my login credential (UserName) on the razor partial page. What can I do?
AppUser user = m_UserSecurity.AuthenticateUserCredentials(UserLogin.LoginID, UserLogin.Password);
HttpContext.Session.SetString("UserName", user.Name);
Try the below code at your razor partial view.
@using Microsoft.AspNetCore.Http
@inject IHttpContextAccessor _httpContext
@{
var userName = _httpContext.HttpContext.Session.GetString("UserName");
}
<div>
My userName is : @userName
</div>
The first method is to use ViewData[xxx], For example, After you setting session in your login action, You want to show the value of session in partial view in Privacy.cshtml, You can get that session in onGet() of PrivacyModel, Then use ViewData["xxx"] to save that value, Finally use @ViewData["xxx"] to get that value in your partial view.
But but I don't recommend this method, In you case, View Component is more suitable for you. Because View component has a "backend", you can use httpcontext to get the session in its "backend" directly. Please refer to this simple demo:
public class UserViewComponent : ViewComponent
{
//inject httpcontext to get the session.
private readonly IHttpContextAccessor _httpContext;
public UserViewComponent(IHttpContextAccessor httpContext)
{
_httpContext = httpContext;
}
public IViewComponentResult Invoke()
{
var username = _httpContext.HttpContext.Session.GetString("UserName");
return View("index",username);
}
}
View
Path: Pages\Shared\Components\User\Index.cshtml
@model string
<h1>This is my view component</h1>
<h1>@Model</h1>
Then use this view component in your page
@await Component.InvokeAsync("User");

btw: Don't forget to register HttpContextAccessor in your program.cs
builder.Services.AddHttpContextAccessor();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With