ASP.NET Razor Newbie Question

How do I check if a session variable is true?  I keep getting an error saying it cannot convert object to bool.

I've tried something like this:

@if (Session["myVariable"] == true) {
  Do something
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

kaufmed   ( ⚆ _ ⚆ )Commented:
This isn't so much a Razor issue as it is a C# one. You have to ensure that you are comparing the same types when using ==. The things you store in Session are stored as type Object. That means when you want to get them out, and treat them like what they actually are, then you need to cast. Simply add a cast to your logic:

@if ((bool)Session["myVariable"] == true) {
  Do something

Open in new window

greddinAuthor Commented:
Thanks kaufmed:

The syntax you give above compiles without error but gives me this error on the page:

"Object reference not set to an instance of an object"

Any ideas?
kaufmed   ( ⚆ _ ⚆ )Commented:
Something is null. You'll have to figure out what. If you can post the code, then I can take a gander.
Learn Ruby Fundamentals

This course will introduce you to Ruby, as well as teach you about classes, methods, variables, data structures, loops, enumerable methods, and finishing touches.

greddinAuthor Commented:
It looks like this:

@if ((bool)Session["isSuperAdmin"] == true) {
    <li><a href="#">Admin Link</a></li>

isSuperAdmin is a bit/boolean field from SQL.  0 or 1
kaufmed   ( ⚆ _ ⚆ )Commented:
If that's the code that is throwing the error, then are you sure you have something assigned to the session key "isSuperAdmin"? You might try instead:

@if (Session["isSuperAdmin"] != null && (bool)Session["isSuperAdmin"] == true) {

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
greddinAuthor Commented:
That worked. I really appreciate your help.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.