Set Session variable in ASP.Net MVC using jQuery


In this tutorial, I will show you how to set a session variable in an ASP/NET MVC using jQuery.

jQuery is a Javascript library, which is a client-side language. Setting a session variable using a client-side function is not possible. So we make an Ajax Call using a jQuery to pass the variable value to the controller and set a session variable.

Now let get started by creating a model Country as shown below.

The Model

    public class EmployeeModel
    public class CountryModel
    {
        public string countryName { get; set; }
    }

The Controller:

        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public JsonResult SetSession(string name)
        {
            Session["CountryName"] = name;
            CountryModel countryModel = new CountryModel()
            {
                countryName = Session["CountryName"].ToString()

            };

            return Json(countryModel);
        }

As you see, the controller contains two methods:

The index() method that takes you to the index page

The SetSession() method that gets triggered when a user clicks on the button.

The View

<br />
<h1>Set Session variable in ASP.Net MVC using jQuery</h1>
    Select a Country:
<select id="ddl">
    <option value="Australia">Australia</option>
    <option value="France">France</option>
    <option value="United Kingdom">United Kingdom</option>
    <option value="United States">United States</option>
</select>

<input type="button" id="btnSet" value="Set Session" />
<script src="https://ajax.googleapis.com/ajax/libs/d3js/5.9.0/d3.min.js"></script>

<script type="text/javascript">
    $(function () {
        $("#btnSet").click(function () {
            $.ajax({
                type: "POST",
                url: "/Home/SetSession",
                data: '{name: "' + $("#ddl").val() + '" }',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    alert("You selected: " + response.countryName);
                }
            });
        });
    });
</script>

Now run the solution; you should get the result below

Set Session in ASP.Net MVC using jQuery

Related Articles

Tutorials Panel

About Tutorials Panel

programming tutorial and source code for Software Engineers and developers. https://twitter.com/TutorialsPanel

View all posts by Tutorials Panel →

Leave a Reply