Introduction
The HttpSessionState.Abandon() method destroys all objects stored in a Session object and releases their resources. We call this method in ASP.Net with Session.Abandon(). This method has no parameters and has no return value.
For using Abandon() method you must add System.Web.dll file to the project and also use System.Web.SessionState namespace in the header page. When this method is called, the current session is not deleted until all of the scripts on the current page have been processed. This means that it is possible to access session variables on some pages as the call to Abandon, but not from another web page.
Syntax
- // Destroys all objects stored in a Session object and releases their resources
- HttpContext.Session.Abandon();
For example in the following script, the Index() method prints the value C-SharpCorner. This is because the Session object is not destroyed until the server has finished processing the script.
- using System.Web.Mvc;
-
- namespace Session.Controllers
- {
- public class HomeController : Controller
- {
-
- public ActionResult Index()
- {
-
- HttpContext.Session.Abandon();
- HttpContext.Session["MyName"] = "C-SharpCorner";
- return View();
- }
- }
- }
View
- <h1>@HttpContext.Session["MyName"]</h1>
Output
C-SharpCorner
Now if you access the variable MyName on a subsequent Web page, it is empty. This is because MyName is destroyed with the previous Session object when the page containing the previous example finished processing.
The server creates a new Session object when you open a subsequent Web page, after abandoning a session. You can store variables and objects in this new Session object.
Problem
If you want to use the Session.Abandon() in Index() method and also the last line in this method, you define a new session with some value that we want in the other page -- select this session to get data value! Value is null because Abandon() method destroys all objects stored in a Session object and releases their resources. What's the solution?
Solution
For solving this problem you define ActionHelper and pass the value that you want to save in the session and use in the other page, now the last process is finished and you can set the value in the new session as in the following sample,
- using System.Web.Mvc;
-
- namespace Session.Controllers
- {
- public class HomeController : Controller
- {
-
- public ActionResult Index()
- {
-
- HttpContext.Session.Abandon();
- HttpContext.Session["MyName"] = "ValueTest";
- return RedirectToAction("ActionHelper", new {helper = "TEST Value.", returnUrl = "/Home/About"});
- }
-
- public ActionResult ActionHelper(string helper, string returnUrl)
- {
- HttpContext.Session["MyName"] = helper;
- return Redirect(returnUrl);
- }
-
-
- public ActionResult About()
- {
- var mode = HttpContext.Session["MyName"];
- return View(mode);
- }
- }
- }
Now you can access the mode variable in the session.