Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Int session variable to increment?

Can a session variable be an int? I want to increment Session["PagesViewed"]+1; every time a page is loaded. I'm getting errors when trying to increment the session variable.

if (Session["PagesViewed"].ToString() == "2")
{
     Session["PagesViewed"] = 0;
}
else
{
     Session["PagesViewed"]++;
}
like image 538
CsharpBeginner Avatar asked Dec 17 '22 05:12

CsharpBeginner


2 Answers

You need to test to see if the Session variable exists before you can use it and assign to it.

You can do increment as follows.

Session["PagesViewed"] = ((int) Session["PagesViewed"]) + 1;

But, if the Session["PagesViewed"] does not exist, this will cause errors. A quick null test before the increment should sort it out.

if (Session["PagesViewed"] != null)
    Session["PagesViewed"] = ((int)Session["PagesViewed"]) + 1;
like image 144
Lion Avatar answered Dec 18 '22 18:12

Lion


Session["PagesViewed"] will only return an Object - which is why your .ToString() call works. You will need to cast this back to an int, increment it there, then put it back in the session.

like image 37
ziesemer Avatar answered Dec 18 '22 19:12

ziesemer