Solved

How to conditionally display content based on a session variable

Posted on 2009-05-13
10
729 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.

 

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

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

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.

Question has a verified solution.

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

In .NET 2.0, Microsoft introduced the Web Site.  This was the default way to create a web Project in Visual Studio 2005.  In Visual Studio 2008, the Web Application has been restored as the default web Project in Visual Studio/.NET 3.x The Web Si…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
This is a high-level webinar that covers the history of enterprise open source database use. It addresses both the advantages companies see in using open source database technologies, as well as the fears and reservations they might have. In this…
If you’ve ever visited a web page and noticed a cool font that you really liked the look of, but couldn’t figure out which font it was so that you could use it for your own work, then this video is for you! In this Micro Tutorial, you'll learn yo…

707 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