session verification masterpage (?) asp.net c# - c#

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">
Home
<% if (Session["permissionUser"] == "1"){ %>
PERMISSION 1 LINK
<% } %>
<% if (Session["permissionUser"] == "2"){ %>
PERMISSION 2 LINK
<% } %>
</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">
Home
<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"){ %>

Related

Hiding a button inside a div from code

I have a aspx page and i want to hide the button from cs file based on my some condition
My .aspx looks like :
<asp: Content Id="contentid" >
<% if (!IsRedeemCardFlowOptin)
{ %>
<ul id="ulid" class="abc">
</ul>
<div class="bcd" id ="div1">
<div id="div2"></div>
<div id="div3"></div>
<div id="div4" runat="server">
<h4><%= m_AutoRenewInfo.NewPageContent.ArCsidOffHeader%></h4>
<button class="abc bcd cde" title="Button" id="buttondiv"><span>Button</span></button> //Want to hide this button
</div>
</div>
<% } %>
</asp:Content>
Now in the cs file i want to hide the button with id "buttondiv", how can i do that
In my cs file, i try this 2 things but it doesnt work
Control myDiv = (Control)FindControl("buttondiv");
myDiv.Visible = false;
Or
foreach (Control c in contentid.Controls)
{
if (c.ID == "buttondiv")
{
c.Visible = false;
}
}
Can anyone let me know
In order to be used as a server-side control, the button would need to be a server-side control. Add runat="server":
<button class="abc bcd cde" title="Button" id="buttondiv" runat="server">
Then (unless you've broken the designer somehow, it's been a while since I've used Web Forms) you should have an HtmlControl object in your class that you can set without the need to "find" the control:
this.buttondiv.Visible = false;
Kindly keep this in css file.
#buttondiv{
display:none;
}
Or apply style inline like below:
<button class="abc bcd cde" title="Button" id="buttondiv" style="display:none"><span>Button</span></button>

ASP form parameter names being changed to include the master page contentplaceholder

Here is my page:
<%# Page Language="C#" MasterPageFile="~/FBMaster.master" CodeFile="ViewOffer.aspx.cs" Inherits="ViewOffer" %>
<asp:Content ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<%
FlightBookingWS.FlightBookingSoapClient client = new FlightBookingWS.FlightBookingSoapClient();
FlightBookingWS.Offer offer = client.GetOffer(Request.Form["OfferID"]);
if (offer != null)
{
%>
<div class="OfferDiv">
<span><b>Origin Airport: </b><%=offer.OriginAirport ?? "" %></span>
<span><b>Destination Airport: </b><%=offer.DestinationAirport ?? "" %></span>
<span><b>Airline: </b><%=offer.Airline ?? ""%></span>
<span><b>Available Seats: </b><%=offer.AvailableSeats%></span>
<span><b>Number Of Connections: </b><%=offer.NumberOfConnections%></span>
<%
if (offer.Fare != null)
{
%>
<span><b>Fare: </b><%=String.Format("{0:0.00} {1}", offer.Fare.Value, offer.Fare.Currency) %></span>
<form runat="server">
<span>
<input type="hidden" id="OfferIDField" runat="server" />
<input type="hidden" id="MessageField" runat="server" />
<b>Number of Seats: </b>
<asp:TextBox ID="NumSeatsField" runat="server" Text="1" />
<asp:Button runat="server" Text="Book now" />
</span>
</form>
<%
}
}
else
{
%>
Offer not found.
<%
}
%>
<div id="ErrorBox" runat="server"></div>
</div>
</asp:Content>
Whenever I submit the form, the keys used in the post data are changed from the IDs I wrote to the following ones:
Ideally I'd like to access them using the same keys as the IDs of the inputs they came from, like in normal HTML.
That's not how ASP.NET web forms work
When you put markup on a page with the runat="server" attribute, you are not actually writing page markup. You are defining server-side controls that emit page markup. You're not meant to use them like actual HTML elements.
When the page is posted back, the ASP.NET framework looks at the request message and parses all of the values. It then populates the server-side controls with the necessary data so you can retrieve it easily using ASP.NET syntax.
So, instead of
var offerID = Request.Form["ctl100$ContentPlaceHolder1#OfferIDField"]
you should simply use
var offerID = this.OfferID.Text;
This is the way ASP.NET web forms work.
The old-fashioned way
If you'd rather do it the old-fashioned way, remove the runat="server" attribute and write your markup like regular HTML:
<INPUT ID="OfferID" Name="OfferID">
...and then you can read it the "normal" way:
var offerID = Request.Form["OfferID"];

How to make user control load once?

I have one user control,named as "SocialShareElements", which's purpose is to share the page content/image into FaceBook.
I utilized this user control in my Index page.
I called this user control in a "IF" condition, within Index.aspx.
The pseudo code is like:
<%
if (Request.IsSecureConnection)
{
%>
<div class="deal-detail-head tzsg-margin-bottom-med">
<MyControl:SocialShareElements ID="SocialShareElements1" runat="server"/>
</div>
<div class="clear-both"></div>
<%
}
else
{
%>
<div class="deal-test bottom-small">
<MyControl:SocialShareElements ID="SocialShareElements" runat="server"/>
</div>
<%
}
%>
When I test the FBShare function in https://developers.facebook.com/tools/debug/og/object/, it showed failed becuase I loaded "SocialShareElements" twice, and this makes meta data of "SocialShareElements" double in Index.aspx.
My question is how to adjust the logic of utilizing "SocialShareElements" in Index.aspx, to make it only be loaded once.
Thank you.
You can achieve this from code-behind.
Modify your div on your aspx page to be available from server side:
<div id="socialShare" runat="server">
</div>
In your code-behind:
protected void Page_Load(object sender, EventArgs e)
{
if(Request.IsSecureConnection)
{
SocialShareElements shareElement = LoadControl("SocialShareElements.ascx") as SocialShareElements;
socialDiv.Controls.Add(shareElement);
}
}

Display A 'Div' Depending On Selection Of Checkbox Value From Another Page

I have a issue. I have an asp.net webform which has a process which stores the data in a session. The issue I can't resolved is that on one of the pages it displays all the details entered throughout the process but one section in only needed to be displayed depending on the selection from my checkboxlist.
HTML for my checkboxlist
<asp:CheckBoxList runat="server" id="Services" CssClass="CheckboxList">
<asp:ListItem Text="All services" Value="All services"></asp:ListItem>
<asp:ListItem Text="Site content uploading only" Value="Site content uploading only"></asp:ListItem>
<asp:ListItem Text="Site content & layout checking" Value="Site content & layout checking"></asp:ListItem>
<asp:ListItem Text="Testing on various browsers" Value="Testing on various browsers"></asp:ListItem>
<asp:ListItem Text="Testing all website functionality" Value="Testing all website functionality"></asp:ListItem>
<asp:ListItem Text="Responsive design (Design/Implemtation only)" Value="Responsive design (Design/Implemtation only)"></asp:ListItem>
<asp:ListItem Text="Responsive design (Testing only)" Value="Responsive design (Testing only)"></asp:ListItem>
</asp:CheckBoxList>
Code behind for the above which stores the selections in the session
private void SessionSaving()
{
List<string> selections = new List<string>();
foreach (ListItem listItem in Services.Items)
{
if (listItem.Selected)
{
selections.Add(listItem.Value);
}
}
Session["Step02Services"] = selections;
}
HTML for my confirmation page
<div class="form-group">
<asp:Label ID="Step04BrowsersLabel" class="col-xs-6 col-sm-3 control-label" runat="server" Text="Browser(s) to check on:"></asp:Label>
<div class="col-xs-6 col-sm-9 form-control-static">
<%= string.Join(", <br />",((List<string>)Session["Step04Browsers"]).ToArray()) %>
<% if (Session["Step04OtherField"] != "")
{%>
<br />
<%=Session["Step04OtherField"] %>
<%} %>
</div>
</div>
I don't want the above section to be displayed if any of the following scenarios checked checkboxes happen:
Site content uploading only
Site content & layout checking only
Site content uploading & Site content & layout checking only
I tried the following if, and it doesn't always displays for me. If I remove the ||'s and just use the first line it hides it for me. If I select the "Site content uploading only" checkbox and another checkbox it also displays if for me (which is correct).
if (string.Join("", ((List<string>)Session["Step02Services"]).ToArray()) != "Site content & layout checking"
|| string.Join(", <br />", ((List<string>)Session["Step02Services"]).ToArray()) != "Site content & layout checking"
|| string.Join("", ((List<string>)Session["Step02Services"]).ToArray()) != "Site content & layout checking" && string.Join(", <br />", ((List<string>)Session["Step02Services"]).ToArray()) != "Site content & layout checking")
How do I write/correct my if above?
My fix was to the HTML on the confirmation page as shown below
if (Session["Step04Browsers"] != null)
{
<div class="form-group">
<asp:Label ID="Step04BrowsersLabel" class="col-xs-6 col-sm-3 control-label" runat="server" Text="Browser(s) to check on:"></asp:Label>
<div class="col-xs-6 col-sm-9 form-control-static">
<%= string.Join(", <br />",((List<string>)Session["Step04Browsers"]).ToArray()) %>
<% if (Session["Step04OtherField"] != "")
{%>
<br />
<%=Session["Step04OtherField"] %>
<%} %>
</div>
</div>
}
I must of had some major brain fart yesterday as this morning it was clear as day. For some reason when i posted this post i was looking at a selction made from my services checkboxlist when infact all i had to do was look at my browser checkboxlist on another page. If it was empty dont display otherwise display it. Can't belive i didnt think of this yesterday.
Wrapped the div in:
if (Session["Step04Browsers"] != null)
You don't even need to store anything in the session you can do this all client side. To get the selected list items you can use:
var checked_checkboxes = $("#<%= Services.ClientID %> input:checked")
Then you can get the value and text as so:
checked_checkboxes.each(function() {
var value = $(this).val();
var text = $(this).closest("td").find("label").html();
}); /* You can also use a for loop */
I suggest changing
<asp:CheckBoxList runat="server" id="Services" CssClass="CheckboxList">
to
<asp:CheckBoxList runat="server" id="Services" CssClass="CheckboxList" onclick="ChangeCheckBox();">
where ChangeCheckBox is a javascript function that gets the selected values as shown above and then hides/shows the div based on what values are selected.

Cookie not displaying on second page load

What I am trying to accomplish is to create a cookie so that after you click a save button, leave the page and then come back to the page, the value of the cookie should be displayed in a label at the top of the page welcoming the user back to the page.
Here is the code I am using.
<%# page language="C#" %>
<%# Import Namespace="System.Data" %>
<%# Import Namespace="System.Data.OleDb" %>
<script language="C#" runat="server">
String welcomeBackName;
void Page_Load(Object sender, System.EventArgs e)
{
if (Page.IsPostBack==true)
{
HttpCookie RUcookie = new HttpCookie("RUcookie");
lblMessage.Text = txtfirstname.Text.Substring(0,1).ToLower() + txtlastname.Text.ToLower() + "#radford.edu";
RUcookie.Value = "Welcome " +txtfirstname.Text +" "+ txtlastname.Text;
RUcookie.Expires = DateTime.Now.AddHours(1);
Response.Cookies.Add(RUcookie);
if(RUcookie != null)
{
welcomeBackName = Request.Cookies["RUcookie"].Value;
welcomeBack.Text = welcomeBackName;
}
}
}
</script>
<html>
<form id=form1 runat="server">
<br>
<ASP:Label id="welcomeBack" Text="" size="60" runat="server"/>
<br>
<br>
<br>
First Name: <asp:TextBox id="txtfirstname" size="20" runat="server"/><br>
<br>
Last Name : <asp:TextBox id="txtlastname" size="20" runat="server"/><br>
<br>
<ASP:Button id="butSave" Text="Save" Autopostback=true runat="server"/>
<br>
<br>
Email: <asp:Label id="lblMessage" size="80" forecolor=Blue runat="server"/><br>
</form>
</html>
Few things wrong.
You said you want this to happen when the user leaves the page and comes back. By definition, you won't be in a postback. That'd be a fresh load of the page. Instead of checking if it's a postback, you should simply check to see if the cookie exists.
The other thing is that IsPostBack is by definition, a boolean. You don't need to check if it's equivalent to true. It's either true or false.

Categories