In this article I will explain with an example, how to set Session variable in JavaScript using jQuery in ASP.Net MVC Razor.
JavaScript is a Client Side language and hence directly it is not possible to set Session variable in JavaScript.
Thus, the solution is to make an AJAX call using jQuery AJAX and pass the value of JavaScript variable to a Controller and inside the Controller the value will be set in Session variable in ASP.Net MVC Razor.
Note: For beginners in ASP.Net MVC, please refer my article ASP.Net MVC Hello World Tutorial with Sample Program example.
 
 
Model
Following is a Model class named PersonModel with two properties i.e. Name and DateTime.
public class PersonModel
{
    ///<summary>
    /// Gets or sets Name.
    ///</summary>
    public string Name { get; set; }
 
    ///<summary>
    /// Gets or sets DateTime.
    ///</summary>
    public string DateTime { get; set; }
}
 
 
Controller
The Controller consists of two Action methods.
Action method for handling GET operation
Inside this Action method, simply the View is returned.
 
Action method for handling jQuery AJAX operation
This Action method handles the call made from the jQuery AJAX function from the View.
Note: For more details on calling Controller using jQuery AJAX function, please refer ASP.Net MVC: jQuery AJAX and JSON Example.
 
Inside the Controller, the value sent from the Client Side is received as parameter and is set into the Session variable.
The value of the Session variable is assigned to the Name property of the PersonModel object along with the Current DateTime and finally the PersonModel object is returned back as JSON to the jQuery AJAX function.
public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        return View();
    }
 
    [HttpPost]
    public JsonResult AjaxMethod(string name)
    {
        Session["Name"] = name;
        PersonModel person = new PersonModel
        {
            Name = Session["Name"].ToString(),
            DateTime = DateTime.Now.ToString()
        };
 
        return Json(person);
    }
}
 
 
View
The View consists of an HTML TextBox element and a Button. The Button has been assigned a jQuery Click event handler.
When the Set Button is clicked, an AJAX call is made to the Controller using jQuery AJAX and the value of the Name TextBox is sent to the Controller.
The Controller then returns a string which 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>
    Your Name :
    <input type="text" id="txtName"/>
    <input type="button" id="btnSet" value="Set Session"/>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $("#btnSet").click(function () {
                $.ajax({
                    type: "POST",
                    url: "/Home/AjaxMethod",
                    data: '{name: "' + $("#txtName").val() + '" }',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (response) {
                        alert("Hello: " + response.Name + " .\nCurrent Date and Time: " + response.DateTime);
                    },
                    failure: function (response) {
                        alert(response.responseText);
                    },
                    error: function (response) {
                        alert(response.responseText);
                    }
                });
            });
        });
    </script>
</body>
</html>
 
 
Screenshot
Set Session variable in JavaScript using jQuery in ASP.Net MVC
 
 
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