How can I access "properties" of TempData in .NET MVC

I have a Student parameter introduced in one of the actions in the controller. I assigned this parameter to TempData["student"] and kept it so that I could use it in another action in the same controller. Now TempData["student"] has sub properties such as FirstName, LastName, Email etc. But since the compiler has no idea about these properties, when I say something like TempData["student"].FirstName in the other action, it throws a compiler error as expected. I initiated a new Student variable in the class level, but since the controller is visited everytime I call an action from the views, it initiates a new variable and resets the values everytime. So I need to access those properties using TempData["student"]. Any help will be appreciated.

Action where I assign values to TempData["student"]

    public ActionResult NewStudentSchedule_Submit(Student student)
        TempData["student"] = student;

        if (TempData.Count() == 0 || TempData == null)
            ViewBag.Error = true;
            ViewBag.Error = false;

        return View("Close");

The way and the action I am trying to use the TempData values in

    public ActionResult StudentApplicants(List<StudentApplicant> studentApplicant)

            Models.Student newStudent = new Models.Student();
            newStudent.FirstName = TempData["student"].FirstName;
            newStudent.LastName = TempData["student"].LastName;
        return View();

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

As I mentioned in my comment, in your StudentApplicants change your code to:

var student = TempData["student"] as Student;

Now you can use student variable and it will hold all the temp data which was set in NewStudentSchedule_Submit

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply