سؤال

I have a blank page with two buttons.

the first button's click code is this:

Session["permissionUser"] = "1";

and here's the second button code:

Session["permissionUser"] = "2";

and then i have a hyperlink which redirects to the "main" website.

my objective is to adapt the menu bar which is on the masterpage based on the permission saved in the session. here's part of my code in the masterpage:

<body>
<div id="menuBar">
<a href="../Default.aspx">Home</a>
<% if (Session["permissionUser"] == "1"){ %>
<a href="#">PERMISSION 1 LINK</a>
<% } %>
<% if (Session["permissionUser"] == "2"){ %>
<a href="#">PERMISSION 2 LINK</a>
<% } %>
</div>

<div id="content">
<asp:ContentPlaceHolder ID="websiteContent" runat="server"></asp:ContentPlaceHolder>
</div>
</body>

the problem is when i run the application, even if i click any of the buttons the menu doesnt adapt at all. it just shows the hyperlink "Home" and not any of the others which were supposed to be shown since the session is either 1 or 2 (depending on which button i clicked)

i cant really see what im doing wrong so if you guys have any suggestions i'd be really grateful

هل كانت مفيدة؟

المحلول

Your code is very PHPish. That is to say, it's ugly. And unwieldy. Let's put the logic in the code behind. We also need a form so we can have controls that run on the server.

public void Page_Load(object sender, EventArgs e)
{
    //you should probably also check to make sure the session has "permissionUser" in it
    if (Session["permissionUser"] == "1")
    {
        Permission1HL.Visible=true;
    }
    else if(Session["permissionUser"] == "2")
    {
        Permission2HL.Visible=true;
    }
}

And change your ASPX page to this.

<body>
<form runat="server">
<div id="menuBar">
<a href="../Default.aspx">Home</a>
<asp:HyperLink runat="server" id="Permission1HL" Text="Permission 1 Link" Visible="false" />
<asp:HyperLink runat="server" id="Permission2HL" Text="Permission 2 Link" Visible="false" />
</div>

<div id="content">
<asp:ContentPlaceHolder ID="websiteContent" runat="server"></asp:ContentPlaceHolder>
</div>
</form>
</body>

نصائح أخرى

I suggest that you make a serverside hyperlink control instead, and set the text and navigateurl from codebehind

<asp:HyperLink id="hyperlink1" 
              NavigateUrl="http://mydefaulturl.com"
              Text="DefaultText"
              runat="server"/>

from code behind:

if (Session["permissionUser"] == 1)
{
  hyperlink1.NavigateUrl = "#"
  hyperlink1.Text = "Permission 1 link"
}...

This will allow you to better control and debug your values.

I would actually be more specific in the if statement

<% if (Session["permissionUser"].toString() == "1"){ %>

with null checks

<% if (Session["permissionUser"] != null && Session["permissionUser"].toString() == "1"){ %>
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top