Ana
Ana

Reputation:

How to access server variable in aspx?

I’ve defined a session variable in my Session_Start procedure

void Session_Start(object sender, EventArgs e)
{

<other stuff>

        string sAdmin= bAdmin.ToString();

        Session["SessionAdmin"] = sAdmin;

}

Then in my masterpage I want to use the Session Variable to conditionally show some links in a list.

How do I write the Boolean expression to correctly access the session variable SessionAdmin?

Here’s what I have:

 <div id="menu">
    <ul>
        <li><a href="/EmployeeTime.aspx">Employee Time</a></li>

        <% if (  *** a Boolean expression involving Session variable "SessionAdmin" *** ) {%>
                     <li><a href="/Employee.aspx">Employees</a></li>
                     <li><a href="/ProductLine.aspx">Product Lines</a></li>
                     <li><a href="/Task.aspx">Tasks</a></li>
                     <li><a href="/Type.aspx">Work Types</a></li>  
                     <li><a href="/Activity.aspx">Activities</a></li>
        <%} %>>  
          </ul>
   </div>

How do I correctly define my boolean expression? I've been looking, but haven't found the right syntax.

Thanks in advance

Upvotes: 1

Views: 3940

Answers (1)

Guffa
Guffa

Reputation: 700192

You have converted the boolean to a string, then stored it in the Session collection which hold Object references, so to get the boolean back you cast the object to get the string, then convert the string to a boolean:

<% if (Convert.ToBoolean((string)Session["SessionAdmin"])) { %>

In some cases, and this one happens to be one, the converter method can also handle the object without first casting:

<% if (Convert.ToBoolean(Session["SessionAdmin"])) { %>

It would be easier if you didn't convert the boolean to a string before storing it in the session variable:

Session["SessionAdmin"] = bAdmin;

Then you only have to unbox it to boolean:

<% if ((bool)Session["SessionAdmin"]) { %>

Upvotes: 3

Related Questions