ASP.NET MVC Session

4

Personal I have a controller where I set two session keys and they capture these key anywhere in the application. (other controller , or a view ).

The controller looks like this:

 [HttpGet]
 public ActionResult TimetableSelect(int currentTimetableId, string currentTimetableName)
 {
     Session["TTBId"] = currentTimetableId;
     Session["TTBName"] = currentTimetableName;
     return RedirectToAction("Dashboard");
 }

But in the view I would refer to the same as below, and is always returning null.

@if (Session["TTBId"] != null && Session["TTBName"] != null)
{
  ....
}

Can anyone tell me what I'm doing wrong?

    
asked by anonymous 24.05.2016 / 18:04

2 answers

3

RedirectToAction opens a new request and thus evaporates data from Session . I would say that this is not the best way to do what you want.

Instead, use TempData , which has a longer lifetime:

[HttpGet]
 public ActionResult TimetableSelect(int currentTimetableId, string currentTimetableName)
 {
     TempData["TTBId"] = currentTimetableId;
     TempData["TTBName"] = currentTimetableName;
     return RedirectToAction("Dashboard");
 }

View :

@if (TempData["TTBId"] != null && TempData["TTBName"] != null)
{
  ....
}
    
24.05.2016 / 19:11
2

I think your code is correct, but its the wrong way to use it.

If by chance the application passes through this method in variavel currentTimetableName does not bring data it is not worth ( null ) and at the time View View does not pass inside that if ( Session )

There is no problem in using Controller with View it does not interfere or erase values if passed correctly!

    
24.05.2016 / 19:53