I have a C# Razor application in .Net5. Within this application I have a partial page without a model. In it I need to dynamically assign the text of a link. However, without a model I'm not sure how best to go about this.
The value is one that will stay the same for the duration that a user will be in the application. However, the value will be different for different users.
Could I hold the value in a cookie, and retrieve this within the partial page? Or is there a better approach?
You could set and get session in razor view/pages like below:
@using Microsoft.AspNetCore.Http
@inject IHttpContextAccessor HttpContextAccessor
@{
HttpContextAccessor.HttpContext.Session.SetString("KeyName", "aaaa");
}
@HttpContextAccessor.HttpContext.Session.GetString("KeyName")
Be sure register session and HttpContextAccessor in Startup.cs:
public class Startup
{
//...
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddSession();
services.AddHttpContextAccessor();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseSession(); //be sure add this...
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
});
}
}