Search code examples
c#asp.net-mvcsessionactionlink

C# MVC ActionLink clear session before reloading page


I have a simple form page, where user can fill some data. After I press post, I need all that data to remain as it is, so if user wants to change data, he/she can. After I save data I store Client object in Session and every time I press Save button, I check if there is user already in Session.

Now I have @Html.ActionLink("New client", "NewUser");, that I press, when I want to create new user. So this link would reload the page and clear that Session.

Note that "New user" should redirect to Index instead, but I managed to get it to work like that, but is not valid way to do so.

Controller code:

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

public ActionResult NewUser()
{
     Session["newClient"] = null;
     return RedirectToAction("Index");
}

Solution

  • clearing the session can only done on backend so you have to make action to clear the session but you dont need return RedirectToAction("Index"); instead return the view

    public ActionResult NewUser()
    {
         Session["newClient"] = null;
         return View("Index",_vm);
    }
    

    since you are redirecting to the index view for creating new user