Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Turning a boolean into session variable

Any ideas how I can turn "edible" in the code into a session to display as a label on a different page?

The label will display a message like "yes can eat"

public int totalCalories()
        {
            return grams * calsPerGram;
        }
        public string getFruitInfo()
        {
            string s;
            if (edible == true)
            {
                s = fName + " is good and it has " + totalCalories() +
 "calories";
            }
            else
            {
                s = "Hands off! Not edible";
                //edible = Sesion ["ediblesesion"] as bool;
                // Session ["ediblesession"] = edible;
            }
            return s;
        }
    }
like image 678
Beep Avatar asked Nov 10 '13 16:11

Beep


1 Answers

You already have the code for setting the session variable in the comment inside the if statement:

Session["ediblesession"] = edible;

However, you probably want to set the session variable outside the if statement, so that it gets a value even if the boolean value is true.

When you want to read the value back in the other page, you will get the boolean value boxed in an object, so you would need to cast it back to a boolean value:

edible = (bool)Session["ediblesession"];

Be careful with the spelling. If you try to read a session variable with the name "ediblesesion" (as in the code in your comment), you won't get the variable that you stored as "ediblesession", and the compiler can't tell you that you made a typo as it's not an identifier.

If you want to read the value, but might come to the page without having set the value first, you would need to check if it exists:

object value = Session["ediblesession"];
if (value != null) {
  edible = (bool)value;
} else {
  edible = false; // or whatever you want to do if there is no value
}
like image 133
Guffa Avatar answered Oct 04 '22 03:10

Guffa