Link to home
Start Free TrialLog in
Avatar of greddin
greddinFlag for United States of America

asked on

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
}
Avatar of kaufmed
kaufmed
Flag of United States of America image

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

Avatar of greddin

ASKER

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?
Something is null. You'll have to figure out what. If you can post the code, then I can take a gander.
Avatar of greddin

ASKER

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
ASKER CERTIFIED SOLUTION
Avatar of kaufmed
kaufmed
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of greddin

ASKER

That worked. I really appreciate your help.