In this article I will explain with an example, how to store Model in Session inside Controller and display in View in ASP.Net MVC Razor.
This article will illustrate how to save Model object in Session variable inside Controller and then access it using Razor syntax inside View in ASP.Net MVC Razor.
Model
The Model class has the following properties.
public class PersonModel
{
public string Name { get; set; }
public string Degree { get; set; }
}
Controller
The Controller consists of the Index Action method. Inside this Action method, the Model class object is stored in Session object and simply the View is returned.
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
PersonModel model = new PersonModel()
{
Name = "Mudassar Khan",
Degree = "BE"
};
Session["Data"] = model;
return View();
}
}
View
Inside the View, the Session object is again type casted back to the Model type and the values are displayed using Razor syntax.
@using Session_Model_MVC.Models
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width"/>
<title>Index</title>
</head>
<body>
<div>
Name: @((Session["Data"] as PersonModel).Name)
<br/>
Degree: @((Session["Data"] as PersonModel).Degree)
</div>
</body>
</html>
Screenshot
Downloads