Solved

How to conditionally display content based on a session variable

Posted on 2009-05-13
10
663 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
Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

 

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

Courses: Start Training Online With Pros, Today

Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
EF5: Question about Metadata Artifact Processing 4 15
imap read mail 1 26
start a process from a service 3 21
C# LINQ ForEach() question 6 17
IntroductionWhile developing web applications, a single page might contain many regions and each region might contain many number of controls with the capability to perform  postback. Many times you might need to perform some action on an ASP.NET po…
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
This tutorial gives a high-level tour of the interface of Marketo (a marketing automation tool to help businesses track and engage prospective customers and drive them to purchase). You will see the main areas including Marketing Activities, Design …
Email security requires an ever evolving service that stays up to date with counter-evolving threats. The Email Laundry perform Research and Development to ensure their email security service evolves faster than cyber criminals. We apply our Threat…

815 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

9 Experts available now in Live!

Get 1:1 Help Now