How to save an object in a session in ASP.NET and access it in a view

I am writing an Asp.Net MVC 4 application. I want to save the model object into a session and then access it from another page, but I don’t know how to do it. Is it possible? For example, some code:

[HttpPost]
    public ActionResult Index(EventDetails obj)
    {

        if (ModelState.IsValid)
        {
            Session["EventDetails"] = obj;
            return RedirectToAction("Index2","Home");
        }
       else return View();

Here's the event detail model code:

namespace ProjectMVC.Models
{
    public class EventDetails
    {
        [Required]
        public string FirstTeamName { get; set; }
    }
}

So, I want to save an EventDetails object in a session, and then get it in the view as a regular object. Something like that:

@Session["EventDetails"].FirstTeamName
+4
source share
1 answer

You need to bind it to the ViewModel:

var vm = (EventDetails)Session["EventDetails"];
return View(vm);

In your view, you simply:

@model EventDetails

@Model.FirstTeamName
+3
source

All Articles