Save and retrieve Session value in Controller and View in ASP.Net MVC

Last Reply on Jul 30, 2018 07:28 AM By mukesh1

Posted on Jul 27, 2018 02:58 AM

I m using session in mvc5.but not bale to find value stored in session on other action or controller.Pls tell how i can maintain session value, untill i can't remove session value.

Posted on Jul 27, 2018 03:39 AM

Hi mukesh1,

Check the below example.

HomeController

public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        Session["Home"] = "Welcome to ASPForums";
        return View();
    }
}

HomeView

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div>
        Home Index Page
        <hr />
        <span>@Session["Home"]</span>
        <br />
        @Html.ActionLink("Send", "Index", "Default")
    </div>
</body>
</html>

DefaultController

public class DefaultController : Controller
{
    // GET: Default
    public ActionResult Index()
    {
        Session["Default"] = Session["Home"];
        return View();
    }
}

DefaultView

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div>
        Default Index Page
        <hr />
        <span>@Session["Default"]</span>
    </div>
</body>
</html>

Screenshot


Posted on Jul 30, 2018 01:20 AM

Posted on Jul 30, 2018 07:28 AM

Use tempdata in place of session