ASP.NET MVC session

Asked

Viewed 730 times

4

Staff I have a controller where Seto two session keys and that capture those key anywhere in the application. (other controller, or a view).

The controller is like this:

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

But in the view I consult equal is below, and is always returning null.

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

Can someone tell me what I’m doing wrong?

  • 4

    Possible duplicate of Persist information using Viewbag?

  • I believe it is not duplicate, perhaps because of the way the information persists for a Session yes, but its initial problem is not the same as that of the link. His problem is information traffic through the system, causing errors in code verification. Bigger problem is the question user’s lack of interaction

2 answers

3

RedirectToAction opens a new request and therefore evaporates the data from Session. I’d say that’s not the best way to do what you want.

Prefer to use instead TempData, who has a longer life span:

[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)
{
  ....
}

2

I believe your code is correct, but your mode of use is wrong.

If by chance the application goes through this method in the variavel currentTimetableName not bring data it is worthless (null) and at the time of the View check does not pass inside that if (@if (TempData["TTBId"] != null && TempData["TTBName"] != null)), because TempData["TTBName"] will be null.

So:

Put a breakpoint both on Controller how much in your View to check the data if they are being sent, and also put in your question the workflow for recording these two variables of Session (Session)

There are no problems in using RedirectToAction with Session it does not interfere with or erase values if they are passed correctly!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.