State management is very important and useful concept in Web
application and also its equally very important that resources can not
be allocated unnecessarily. In ASP.NET MVC we can manage the session
controller specific which helps to disable the session when you don't
require IT for particular controller and due to this we can improve the
performance of an application by freeing resources not needed to be
allocated. Now you might be thinking that how it will be possible ?, So
its possible with the help of controller attribute SessionState.
Now let us learn about the SessionState attribute in brief so it will be useful to understand easily.
Example
This property is very important when you want to disable the session for controller specific where there is no need to maintain the session.
Example:
Example
Example
I hope you have understand about the SessionState from preceding
brief summary. Now let's implement it practically, How to manage session
at controller specific
Step 1 : Create an MVC application.
Right click on Model folder in the created MVC application and add class named EmpModel and right the following lines of code as.
Step 3: Add user and admin controller controller.
Right click on Controller folder in the created MVC application and add the controller class as:
Now after selecting controller template, click on add button then the following window appears,
Step 4: Add strongly typed view as:
Right click on view folder in the created MVC application and add view named Index from EmpModel class as.
Now the form code automatically get generated into the Index.cshtml view and modify it by writing the code to read session value if the session is enabled. After modifying the code, view.cshtml source code will be like the following,
In the above null reference exception occur because we disabled the session for this controller and tried to use session, that's why the null reference exception occurred.
It is a good practice that there is no need to maintain the session for specific controller in your application, then disable it which will really improve the performance of your application.
Now let us enable the session, set Session state behavior to default as:
The above output get displayed because we have enabled the session at controller level. I hope from all the preceding examples, you have learned how to set manage session at controller specific in ASP.NET MVC.
Note:
I hope this article is useful for all readers. If you have any suggestions, then please mention it in the comment section.
Now let us learn about the SessionState attribute in brief so it will be useful to understand easily.
What is SessionState
Session State is the attribute of controller class which is used to control or manage the default session behavior.To use session state attribute we need to use System.Web.SessionState namespace.
The following are the behavior of the Session State attribute
Session State is the attribute of controller class which is used to control or manage the default session behavior.To use session state attribute we need to use System.Web.SessionState namespace.
The following are the behavior of the Session State attribute
- Default
- Disabled
- Required
- ReadOnly
- Default
Example
[SessionState(SessionStateBehavior.Default)] public class HomeController : Controller { // Action methods }
- Disabled
This property is very important when you want to disable the session for controller specific where there is no need to maintain the session.
Example:
[SessionState( SessionStateBehavior.Disabled)] //controller public class HomeController : Controller { // Action methods }
- Required
Example
[ SessionState( SessionStateBehavior.Required)] //controller public class HomeController : Controller { // Action methods }
- ReadOnly
Example
[ SessionState( SessionStateBehavior.ReadOnly)] //controller public class HomeController : Controller { // Action methods }
Step 1 : Create an MVC application.
- "Start", then "All Programs" and select "Microsoft Visual Studio 2015".
- "File", then "New" and click "Project" then select "ASP.NET Web Application Template", then provide the Project a name as you wish and click on OK.
- Choose MVC empty application option and click on OK
Right click on Model folder in the created MVC application and add class named EmpModel and right the following lines of code as.
EmpModel.cs
public class EmpModel { public string Name { get; set; } }
Right click on Controller folder in the created MVC application and add the controller class as:
Now after selecting controller template, click on add button then the following window appears,
Specify
the controller name and click on add button, Now open the
HomeController.cs file and write the following code into the Home
controller class as:
HomeController.cs
HomeController.cs
using System; using System.Web.Mvc; using SessionStateAttributeInMVC.Models; using System.Web.SessionState; namespace SessionStateAttributeInMVC.Controllers { [ SessionState( SessionStateBehavior.Disabled)] public class HomeController : Controller { // GET: Home public ActionResult Index() { return View(); } [HttpPost] public ActionResult Index(EmpModel obj) { //store the session from user input and display into the view if session is enabled. Session["Name"] = Convert.ToString(obj.Name); return View(); } } }
In the above code , We have created home controller and
defined SessionState attribute with Disabled behavior and in Post action
method we are storing user input value into session and returning to
the index view where we will display the session value.
Right click on view folder in the created MVC application and add view named Index from EmpModel class as.
Now the form code automatically get generated into the Index.cshtml view and modify it by writing the code to read session value if the session is enabled. After modifying the code, view.cshtml source code will be like the following,
@model SessionStateAttributeInMVC.Models.EmpModel @{ ViewBag.Title = "www.compilemode.com"; } @using (Html.BeginForm()) { @Html.AntiForgeryToken() <div class="form-horizontal"> <h4>EmpModel</h4> <hr /> @Html.ValidationSummary(true, "", new { @class = "text-danger" }) <div class="form-group"> @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" }) </div> </div> @if (Session["Name"] != null) { //if session is enabled then display the session value @Html.Label(Convert.ToString(Session["Name"]), htmlAttributes: new { @class = "control-label col-md-4" }) } <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <input type="submit" value="Create" class="btn btn-default" /> </div> </div> </div> }
Now run the application and the following error will occur.
In the above null reference exception occur because we disabled the session for this controller and tried to use session, that's why the null reference exception occurred.
It is a good practice that there is no need to maintain the session for specific controller in your application, then disable it which will really improve the performance of your application.
Now let us enable the session, set Session state behavior to default as:
using System; using System.Web.Mvc; using SessionStateAttributeInMVC.Models; using System.Web.SessionState; namespace SessionStateAttributeInMVC.Controllers { [ SessionState( SessionStateBehavior.Default)] public class HomeController : Controller { // GET: Home public ActionResult Index() { return View(); } [HttpPost] public ActionResult Index(EmpModel obj) { //store the session from user input and display into the view if session is enabled. Session["Name"] = Convert.ToString(obj.Name); return View(); } } }
Now run the application and input some value into the textbox, then it will get back displayed using session in view as:
The above output get displayed because we have enabled the session at controller level. I hope from all the preceding examples, you have learned how to set manage session at controller specific in ASP.NET MVC.
Note:
- Download the Zip file of the sample application for a better understanding.
- Apply proper validation before using it in your project.
I hope this article is useful for all readers. If you have any suggestions, then please mention it in the comment section.
Post a Comment