In this article I will explain with an example, how to store Custom class object in Session in ASP.Net Core MVC.
Model
The Model class consists of following properties.
public class PersonModel
{
public string Name { get; set; }
public int Age { get; set; }
}
Namespaces
You will need to import the following namespace in both the Controllers.
Controllers
Source Controller
The Controller consists of following Action method.
Action method for handling GET operation
Inside this Action method, an object of PersonModel class is created and its properties are set.
Note: Session class does not have any provision to store objects and hence objects must be serialized to string and then stored.
Then, the object is converted into a
JSON string (parsed) using
SerializeObject method of
JsonConvert class and stored in
Session using
SetString method.
Finally, using the RedirectToAction method the page is redirected to destination Controller.
public class HomeController : Controller
{
public IActionResult Index()
{
//Create a Custom class object.
PersonModel person = new PersonModel
{
Name = "Mudassar Khan",
Age = 39
};
//Convert Person class object to JSON.
string personJSON = JsonConvert.SerializeObject(person);
//Set the JSON String value in Session object.
HttpContext.Session.SetString("Person", personJSON);
return RedirectToAction("Index", "PersonDetails");
}
}
Destination Controller
The Controller consists of the following Action method.
Action method for handling GET operation
Inside this Action method, the
JSON string is fetched from
Session using its
GetString method and then it is deserialized into
PersonModel class object using
DeserializeObject method of
JsonConvert class.
Finally, the PersonModel class object is returned to the View.
public class PersonDetailsController : Controller
{
public IActionResult Index()
{
//Get the JSON string from the Session object.
string? personJSON = HttpContext.Session.GetString("Person");
//Deserialize the JSON string to Person class object.
PersonModel? person = JsonConvert.DeserializeObject<PersonModel>(personJSON);
//Return the Person class object to View.
return View(person);
}
}
View
HTML Markup
Source View
The View is kept empty, as it is not required.
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
</body>
</html>
Destination View
Inside the View, the PersonModel class is declared as Model for the View.
Here, the Model property values are displayed.
@model Session_Object_Core.Models.PersonModel
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
Name: @Model.Name
<br />
Age: @Model.Age
</body>
</html>
Screenshot
Downloads