Home > Software engineering >  ASP.NET Core (document).ready read session value
ASP.NET Core (document).ready read session value

Time:09-30

I am writing an ASP.NET Core MVC 6 app.

In the controller, I am setting a session variable:

HttpContext.Session.SetString("PrimaryNavigation", "First");

I need to retrieve that value in _Layout.cshtml:

<script language="javascript" type="text/javascript">
    $(document).ready(function () {
        alert('<%= Session("PrimaryNavigation")%>');
    });
</script>

But the alert shows

'<%= Session("PrimaryNavigation")%>'

instead of its value.

In all application using Javascript, I made it run. But it seems with jQuery and ASP.NET Core, it is different.

What I am missing?

Thanks

CodePudding user response:

Try below:

1.Register IHttpContextAccessor and session in Program.cs

builder.Services.AddSession();
builder.Services.AddHttpContextAccessor();
...
app.UseSession();

2.In _Layout.cshtml, inject IHttpContextAccessor implementation and use it to get the HttpContext and Session object from that.

@using Microsoft.AspNetCore.Http
@inject IHttpContextAccessor HttpContextAccessor
<script language="javascript" type="text/javascript">
    $(document).ready(function () {
         alert('@HttpContextAccessor.HttpContext.Session.GetString("PrimaryNavigation")');
    });
</script>

3.result:

enter image description here

  • Related