dantey89
dantey89

Reputation: 2287

How to save object to session in ASP.NET & access it in View

I am writing Asp.Net MVC 4 application. I want to save model object to session and then access it from another page but 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 Event details model code:

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

So I want to save EventDetails object to session and then access it in View like a normal object. Something like this:

@Session["EventDetails"].FirstTeamName

Upvotes: 4

Views: 4662

Answers (1)

beautifulcoder
beautifulcoder

Reputation: 11330

You need to bind it to a ViewModel:

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

In your view you simply:

@model EventDetails

@Model.FirstTeamName

Upvotes: 3

Related Questions