Solved

How to conditionally display content based on a session variable

Posted on 2009-05-13
10
654 Views
Last Modified: 2012-05-06
One thing I did a lot of in Classic ASP involved showing page elements conditionally based on a session varriable I set.  For instances, if the value of the session variable was "general" the user would get a little big of content and a couple of controls.  If the value was "advanced" they would get MORE content and additional controls.  Keep in mind this is all on the same page.

I would like to know generally how this is done in ASP.NET.

Again, I'd like to show folks a minimal version of the page, and show logged-in folks
a lot more.

Back in the day of Classic ASP I just check the value of my session variable and did an If... EndIf

<%
If session("type") = "General" then
%>
<p> You have the ability to update this page.  Congrats!</p>
      <!-- Show them the UPDATE button -->
<%
End if
%>

But everything in ASP.NET is done via the code behind and I have no idea how to inject this sort of stuff from the code behind to the aspx page at the EXACT location I need the code to appear.

Can someone provide a best pratice example on how do do this?
0
Comment
Question by:cdemott33
  • 4
  • 3
  • 2
  • +1
10 Comments
 
LVL 10

Accepted Solution

by:
MaxOvrdrv2 earned 250 total points
ID: 24378414
here's how: declare ALL of your controls, but set their Visible attributes to FALSE... then in the code-behind, reference the session the same way you did with Pure ASP, and set the Visible property of the approriate control accordingly...
HTML page:
 

<asp: Button id="btn" runat="server" text="Only if the session is here!" Visible="False" />
 

Code-Behind:
 

if Session("TheSession")<>"" AND IsDBNull(Session("TheSession"))=false then

   Me.btn.Visible=True

end if

Open in new window

0
 
LVL 18

Expert Comment

by:carlnorrbom
ID: 24378483
Or if you don't want to do it declaratively You would typically add <asp:PlaceHolder ID="phUserTools" runat="server" /> in your aspx page where you want user controls to go and a <asp:PlaceHolder ID="phAdminTools" runat="server" /> where you want the admin tools for instance. And then in Your code behind, in the Page_Init or Page_Load event (very simple put..):

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    Dim btnUserButton As New Button()
    btnUserButton.ID = "usrButton"
    btnUserButton.Text = "User Action"
    AddHandler btnUserButton.Click, AddressOf SomeFunction
    phUserTools.Controls.Add(btnUserButton)
    If Session("UserMode") = "Admin" 'User is admin...
        Dim btnAdminButton As New Button()
        btnAdminButton.ID = "admButton"
        btnAdminBUtton.Text = "Admin Action"
        AddHandler btnAdminButton.Click, AddressOf SomeAdminFunction
        phAdminTools.Controls.Add(btnAdminButton)
    End If
End Sub

/Carl.
0
 
LVL 10

Expert Comment

by:MaxOvrdrv2
ID: 24378522
Yes, however, with that version, since they are all dynamic controls, you will have to re-declare/create those controls every time the page loads... it works, i just find it uses up more processor power than is required... visible will use the processor once, and then you're done... but whatever works best for you there cdemott33
0
 

Author Comment

by:cdemott33
ID: 24379357
Thanks for your feed back.  I added a div take and set its ID to  "availableQuantity "  The problem I'm having now it the code behind isn't recoginzing the DIV id?   When I enter the ID in my code behind I'm getting the following error:

Name availableQuantity is not declared

How do I fix this?

<!-- ASPX PAGE -->
 

        <asp:Repeater ID="itemsFound" runat="server">

        <HeaderTemplate>

        <table>

        </HeaderTemplate>

        <ItemTemplate>

        <tr>

        <td>

            <img alt="<%#DataBinder.Eval(Container.DataItem, "Product_SKU")%>" src="<%#DataBinder.Eval(Container.DataItem, "product_image_url")%>Thumbnail.jpg" />

            <div id="totalQuantity">

            Total Quantity: <%#DataBinder.Eval(Container.DataItem, "product_quantity")%>

            </div>

            <div id="availableQuantity" visible="false" runat="server">

            Available Quantity: <%#DataBinder.Eval(Container.DataItem, "product_quantity_out")%> 

            </div>

            

            </td>

        </tr>

        </ItemTemplate>

        <FooterTemplate>

        </table>

        </FooterTemplate>

        </asp:Repeater>

Open in new window

0
 
LVL 18

Expert Comment

by:carlnorrbom
ID: 24379623

Hi,
I think it's because it's nested inside the asp repeater. You can probably reference it from code behind using
Dim div As HtmlContainer = CType(itemsFound.FindControl("availableQuantity"), HtmlContainer)
I'm not sure about the HtmlContainer though, could be You shoulf be using HtmlGenericControl("DIV") or something, I don't have my dev environment up and running at the moment.
/Carl.
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 8

Assisted Solution

by:ppittle
ppittle earned 250 total points
ID: 24381798
Personal preference, I would do something like this:

<asp:Repeater ID="itemsFound" runat="server">
<div id="availableQuantity" visible='<%# DisplayAvailableQuantity() %'>
            Available Quantity: <%#DataBinder.Eval(Container.DataItem, "product_quantity_out")%>
            </div>

<%--  Code Behind--%>
protected bool DisplayAvailableQuantity()
if (Session("TheSession")<>"" AND IsDBNull(Session("TheSession"))==false)
  return True
end if

I think it's a little cleaner to use a method call from the declarative declaration that returns a bool value indicating if the div should be visibile or not.  That way your code behind isn't hunting for Controls.
0
 
LVL 10

Expert Comment

by:MaxOvrdrv2
ID: 24383725
the reason why your DIV isn't being recognized is that you must set the runat="Server" property to it... and if you're working in VS2003, you will have to go from HTML view to Desgin view, then back to HTML, then hit Ctrl-Z twice to get your original code back... that should register all of that stuff for you in the backed... if you're NOT working with VS2003... skip the final steps... just add runat="server"

Cheers!
0
 

Author Comment

by:cdemott33
ID: 24384906
I tried ppittle solution and, with a slight modification, it worked.  All I had to do was set the runat="server" on my div tag and BINGO, it worked.   In case someone else needs to do this in the future here's my code snippet (In VB).

Thanks everyone for your input.
<!-- ASPX PAGE WITH REPEATER CONTROL -->
 

        <asp:Repeater ID="itemsFound" runat="server">

        <HeaderTemplate>

        <table>

        </HeaderTemplate>

        <ItemTemplate>

        <tr>

        <td>

            <img alt="<%#DataBinder.Eval(Container.DataItem, "Product_SKU")%>" src="<%#DataBinder.Eval(Container.DataItem, "product_image_url")%>Thumbnail.jpg" />

            

            <div id="totalQuantity">

            Total Quantity: <%#DataBinder.Eval(Container.DataItem, "product_quantity")%>

            </div>
 

            <div id="availableQuantity" visible="<%# DisplayAvailableQuantity()%>" runat="server">

            Available Quantity: <%#DataBinder.Eval(Container.DataItem, "product_quantity_out")%> 

            </div>
 

            </td>

        </tr>

        </ItemTemplate>

        <FooterTemplate>

        </table>

        </FooterTemplate>

        </asp:Repeater>
 

<!-- CODE BEHIND PAGE - IN VB -->
 

    Function DisplayAvailableQuantity() As Boolean

        If Session("type") = "general" Then

            Return False

        End If

    End Function

Open in new window

0
 

Author Closing Comment

by:cdemott33
ID: 31581164
Thanks All!
0
 
LVL 10

Expert Comment

by:MaxOvrdrv2
ID: 24384928
told you all you needed was the runat="server" ;-)
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Just a quick little trick I learned recently.  Now that I'm using jQuery with abandon in my asp.net applications, I have grown tired of the following syntax:      (CODE) I suppose it just offends my sense of decency to put inline VBScript on a…
In an ASP.NET application, I faced some technical problems. In this article, I list them out and show the solutions that I found.  I hope it will be useful. Problem: After closing a pop-up window, the parent page should be refreshed automaticall…
This video demonstrates how to create an example email signature rule for a department in a company using CodeTwo Exchange Rules. The signature will be inserted beneath users' latest emails in conversations and will be displayed in users' Sent Items…
Delivering innovative fully-managed cloud services for mission-critical applications requires expertise in multiple areas plus vision and commitment. Meet a few of the people behind the quality services of Concerto.

948 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now