In this article I will explain with an example, how to get Session value in JavaScript in ASP.Net MVC Razor.
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 MVC Razor.
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 ActionResult Index()
{
Session["Person"] = "Mudassar";
return View();
}
[HttpPost]
public JsonResult AjaxMethod(string sessionName)
{
return Json(Session[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() + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
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
Browser Compatibility
The above code has been tested in the following browsers.
* All browser logos displayed above are property of their respective owners.
Downloads