In this article I will explain with an example, how to get Session value in JavaScript or jQuery in ASP.Net Core MVC.
JavaScript is a Client Side language and hence directly it is not possible to get Session value in JavaScript.
Thus, the solution is to make an AJAX call using jQuery AJAX function and pass the value of JavaScript variable to a Controller and inside the Controller the value is retrieved from Session object in ASP.Net Core MVC.
Note: For beginners in ASP.Net MVC Core, please refer my article ASP.Net MVC Core Hello World Tutorial with Sample Program example.
 
 
Configuring the AJAX and JSON Serializer setting
The first step is to configure the JSON Serializer settings in the Startup.cs file.
1. Open the Startup.cs class from the Solution Explorer window.
ASP.Net Core: Get Session value in JavaScript or jQuery
 
2. Add the following namespace.
using Newtonsoft.Json.Serialization;
 
3. Then inside the ConfigureServices method, you will have to add the following code which will instruct the program to use Newtonsoft library for JSON serialization.
public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc()
            .AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());
}
 
Note: For more details on configuration and usage of jQuery AJAX in ASP.Net Core, please refer ASP.Net Core: jQuery AJAX and JSON Example in ASP.Net Core MVC.
 
 
Enabling the Session
Session can be enabled using the Configure method.
Inside this method, you will have to call the UseSession method of the app object.
Note: It is mandatory to call the UseSession method before the UseMvc method.
 
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    //Enable Session.
    app.UseSession();
 
    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });           
}
 
Note: For more details on configuration and enabling of Session in ASP.Net Core, please refer Enable Session in ASP.Net Core.
 
 
Controller
The Controller consists of two Action methods.
Action method for handling GET operation
Inside this Action method, Session object is set and the View is returned.
 
Action method for handling jQuery AJAX operation
This Action method handles the jQuery AJAX call made from the View.
Inside the Controller, the Session variable name sent from the Client Side is received as parameter and value is retrieved from Session object.
Finally, the Session object is returned.
public class HomeController : Controller
{
    // GET: Home
    public IActionResult Index()
    {
        HttpContext.Session.SetString("Person", "Mudassar");
        return View();
    }
 
    [HttpPost]
    public IActionResult AjaxMethod(string sessionName)
    {
        return Json(HttpContext.Session.GetString(sessionName));
    }
}
 
 
View
The View consists of an HTML TextBox element and a Button. The Button has been assigned a jQuery Click event handler.
When the Get Session Button is clicked, an AJAX call is made to the Controller using jQuery AJAX function and the value of the TextBox is sent to the Controller.
Finally, the Session value is displayed using JavaScript Alert Message Box.
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    Session:
    <input type="text" id="txtSessionName" />
    <input type="button" id="btnGet" value="Get Session" />
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $("#btnGet").click(function () {
                $.ajax({
                    type: "POST",
                    url: "/Home/AjaxMethod",
                    data: { "sessionName": $("#txtSessionName").val() },
                    success: function (response) {
                        if (response != null) {
                            alert(response);
                        } else {
                            alert("Session object not found.");
                        }
                    },
                    failure: function (response) {
                        alert(response.responseText);
                    },
                    error: function (response) {
                        alert(response.responseText);
                    }
                });
            });
        });
    </script>
</body>
</html>
 
 
Screenshot
ASP.Net Core: Get Session value in JavaScript or jQuery
 
 
Browser Compatibility

The above code has been tested in the following browsers.

Internet Explorer  FireFox  Chrome  Safari  Opera 

* All browser logos displayed above are property of their respective owners.

 
 
Downloads