Improve company productivity with a Business Account.Sign Up

x
?
Solved

How to conditionally display content based on a session variable

Posted on 2009-05-13
10
Medium Priority
?
935 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 1000 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
Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 

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
 
LVL 8

Assisted Solution

by:ppittle
ppittle earned 1000 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

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Today is the age of broadband.  More and more people are going this route determined to experience the web and it’s multitude of services as quickly and painlessly as possible. Coupled with the move to broadband, people are experiencing the web via …
There is a wide range of advantages associated with the use of ASP.NET. This is why this programming framework is used to create excellent enterprise-class websites, technologies, and web applications.
Free Data Recovery software is an advanced solution from Kernel Tools to recover data and files such as documents, emails, database, media and pictures, etc. It supports recovery from physical & logical drive after a hard disk crash, accidental/inte…
Through the video, you can check the migration process of Outlook PST file to PDF. Kernel for Outlook to PDF tool can convert Outlook emails with all attributes like Subject, To, From, Cc, Bcc and other folders such as Inbox, Outbox, Sent Items, Jun…

595 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