Solved

How to conditionally display content based on a session variable

Posted on 2009-05-13
10
650 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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility

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
Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

 
LVL 8

Assisted Solution

by:ppittle
ppittle earned 250 total points
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
Thanks All!
0
 
LVL 10

Expert Comment

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

Featured Post

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

Microsoft Reports are based on a report definition, which is an XML file that describes data and layout for the report, with a different extension. You can create a client-side report definition language (*.rdlc) file with Visual Studio, and build g…
A quick way to get a menu to work on our website, is using the Menu control and assign it to a web.sitemap using SiteMapDataSource. Example of web.sitemap file: (CODE) Sample code to add to the page menu: (CODE) Running the application, we wi…
Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

744 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

14 Experts available now in Live!

Get 1:1 Help Now