Creating custom cookies - c#

Here is the problem, first i will copy the code then i will explain what problem is.
protected void Page_Load(object sender, EventArgs e)
{
CheckIfCookieExists();
}
bool CheckIfCookieExists()
{
HttpCookie cookie = new HttpCookie("accpetedCookie");
cookie.Values.Add("username", "user");
cookie.Expires = DateTime.Now.AddYears(1);
Response.Cookies.Add(cookie);
HttpCookie myCookie = Request.Cookies["accpetedCookie"];
if (myCookie == null)
{
return false;
}
if (!string.IsNullOrEmpty(myCookie.Values["username"]))
{
return true;
}
else
{
return false;
}
}
protected void OKButton_Click(object sender, EventArgs e)
{
if (!CheckIfCookieExists())
{
pnlDialog.Visible = true;
}
else
{
pnlDialog.Visible = false;
}
}
so on page load there is panel and ask client do you accept cookies if click yes goes to OKButton, and after the cookies are stored in browser(i can see them in resources) and when i click on other page on the same site, then the panel appears againg and ask me for the cookies. This is HTML side.
<div id="dialog-content">
<asp:Panel ID="pnlDialog" title="Cookies policy" runat="server">
<div id="dialog">
<p>
If you agree to accept cookies click Yes, otherwise click No!</p>
<div class="popup-btn-content">
<div class="popup-ok-btn">
<asp:Button runat="server" Text="Yes" ID="OKButton" onclick="OKButton_Click"
style="height: 26px" /></div>
<div class="popup-exit-btn">
<asp:Button runat="server" Text="No" ID="ExitButton"
onclick="ExitButton_Click" OnClientClick="return hidePanel()" /></div>
</div> </div>
</asp:Panel>
</div>

Try putting a !IsPostBack() around your Page_Load code like this:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack())
CheckIfCookieExists();
}
I think that if you set/check the cookie on non postbacks, the cookie should remain.

Related

ASP.net textbox with range textmode keeps resetting it's value

Hi i am busy creating a asp.net project that needs to get three values from the user. I am using a textbox with a range textmode to get these values and the first time the user moves the slider it works perfectly but after that the user can.t adjust any of the textboxes anymore.
I tried using a slider extender but this does not seem to work and only a textbox shows.
my html code to create the textboxes and labels showing the value
body>
<form id="form1" runat="server">
<p>
Quantum 1 Length:
<asp:TextBox ID="txtVal1" runat="server" TextMode="Range" min="1" Max="8" OnTextChanged="txtVal1_TextChanged1" AutoPostBack="True"></asp:TextBox>
<asp:Label ID="lblVal1" runat="server" Text="/////"></asp:Label>
</p>
<p>
Quantum 2 Length:
<asp:TextBox ID="txtVal2" runat="server" TextMode="Range" min="1" Max="8" OnTextChanged="txtVal2_TextChanged1" AutoPostBack="True"></asp:TextBox>
<asp:Label ID="lblVal2" runat="server" Text="/////"></asp:Label>
</p>
<p>
Quantum 3 Length:
<asp:TextBox ID="txtVal3" runat="server" TextMode="Range" min="1" Max="8" AutoPostBack="True" OnTextChanged="txtVal3_TextChanged1"></asp:TextBox>
<asp:Label ID="lblVal3" runat="server" Text="/////"></asp:Label>
</p>
<p>
<asp:Button ID="btnNext" runat="server" AutoPostBack="true" Height="24px" OnClick="btnNext_Click" style="margin-left: 0px" Text="Next" Width="150px" />
<script type="text/javascript" __designer:mapid="129">
function NextPage() {
window.open('Execution.aspx', 'Execution');
}
</script>
<asp:Label ID="lblError" runat="server" ForeColor="Red" Text="Invalid input; Please ensure that Quantum 1 <= Quantum 2 <= Quantum 3" Visible="False"></asp:Label>
</p>
</form>
</body>
My C# code used to control the boxes and change their values
public partial class Quantums : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
try
{
txtVal1.Text = HttpContext.Current.Session["Q1"].ToString();
}
catch { }
try
{
txtVal2.Text = HttpContext.Current.Session["Q2"].ToString();
}
catch { }
try
{
txtVal3.Text = HttpContext.Current.Session["Q3"].ToString();
}
catch { }
lblVal1.Text = txtVal1.Text;
lblVal2.Text = txtVal2.Text;
lblVal3.Text = txtVal3.Text;
//UpdatePanel1.Triggers.Add(new AsyncPostBackTrigger() { ControlID = "btnNext" });
}
protected void txtVal1_TextChanged1(object sender, EventArgs e)
{
HttpContext.Current.Session["Q1"] = txtVal1.Text;
}
And then the same code for textbox 2 and 3. Any suggestions on why the textboxes vaklue keeps resetting and autopostback is enabled on all three buttons.
I just noticed you were missing if(Page.IsPostBack()) return;. Your problem is that every time you change your textbox, the 'Page_Load' event is enacted, then the respective event handler (see page life cycle). So you were setting the text to the sessions, then setting the sessions to the text, effectively doing nothing.
You actually don't need anything for this page in the Page_load method, at least for now. Try the following:
protected void Page_Load(object sender, EventArgs e)
{
}
protected void txtVal1_TextChanged(object sender, EventArgs e)
{
Session["Q1"] = txtVal1.Text;
lblVal1.Text = txtVal1.Text;
}
protected void txtVal2_TextChanged(object sender, EventArgs e)
{
Session["Q2"] = txtVal2.Text;
lblVal2.Text = txtVal2.Text;
}
protected void txtVal3_TextChanged(object sender, EventArgs e)
{
Session["Q3"] = txtVal3.Text;
lblVal3.Text = txtVal2.Text;
}
You can then access the user input values using the respective session values. For example:
protected void Submit(object sender, EventArgs e)
{
List<string> answers = new List<string>();
answers.Add(Session["Q1"].ToString());
answers.Add(Session["Q2"].ToString());
answers.Add(Session["Q3"].ToString());
// Do stuff with answers
}

How can update usercontrol in masterpage

I have a master page and an user control on it.
I have a two buttons in the user control for create or remove session, and a label that shows a session text, when click the buttons nothing happens and user control doesn't update I should refresh the page,
Would you please anybody help me to fix this issue ?
This is my master page markup:
<form runat="server">
<div>
<!--previous codes-->
<nav class="navigation">
<div class="wrapper">
<controller:menu runat="server" ID="menu" />
<controller:user runat="server" ID="user" />
</div>
</nav>
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
<!--Next Codes-->
</div>
</form>
and this is my user control
<ul class="nav signup">
<li class="no-drop-down">
<asp:Label ID="_signupbutton" runat="server" CssClass="sr">Test</asp:Label>
<div class="signup-dropdown">
<asp:PlaceHolder ID="_defaultuser" runat="server" Visible="false">
<div class="notloggeduser">
<asp:LinkButton ID="LinkButton1" runat="server" CssClass="usercontroller"
OnClick="LinkButton1_Click" Text="????">
</asp:LinkButton>
</div>
</asp:PlaceHolder>
<asp:PlaceHolder ID="_signedup" runat="server" Visible="false">
<div class="defaultuser">
<ul>
<li>
<asp:LinkButton ID="_userlogout" runat="server" CssClass="usercontroller" OnClick="_userlogout_Click">
<i class="fa"></i>????
</asp:LinkButton>
</li>
</ul>
</div>
</asp:PlaceHolder>
</div>
</li>
</ul>
and this is user control codebehind
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Session["signup"] == null)
{
_signupbutton.Text = "??? ??? / ????";
_defaultuser.Visible = true;
}
else
{
_signupbutton.Text = "<i class=\"fa\"></i> " + Session["signup"].ToString();
_signedup.Visible = true;
}
}
}
protected void _userlogout_Click(object sender, EventArgs e)
{
Session.Remove("signup");
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
Session.Add("signup", "????? ??????????");
}
Your order of events is a bit messed up here.
Page_Load will execute before the event handlers for the click events. You need to perform the setup of the button state from the event handlers, as if you do it in page load your session object wont have been updated yet.
You will need to do a few things here (this isn't tested but should show you the logic):
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) // This will run when the page is loaded but not from a post back / button click etc (e.g. from your page refresh)
{
this.SetButtonState();
}
else
{
// use this for things you want to happen on postback only
}
}
private void SetButtonState()
{
if (Session["signup"] == null)
{
_signupbutton.Text = "??? ??? / ????";
_defaultuser.Visible = true;
}
else
{
_signupbutton.Text = "<i class=\"fa\"></i> " + Session["signup"].ToString();
_signedup.Visible = true;
}
}
protected void _userlogout_Click(object sender, EventArgs e)
{
Session.Remove("signup");
// Update your button state
this.SetButtonState();
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
Session.Add("signup", "????? ??????????");
// Update your button state
this.SetButtonState();
}

Text property of a TextBox is empty when an async PostBack occurs

I've had a look at lots of posts and I feel like I'm going crazy as nothing I've tried seems to work. I simply want to click a button and retrieve the value of a textbox.
I'm using web forms with a site.master so not sure if this could be affecting the problem, but most of the solutions I've seen don't appear to be using a site.master.
I'm not binding the textbox, initially I just wanted to create a contact form.
<%# Page Title="About" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="About.aspx.cs" Inherits="Blackburn_Pulse.About" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<script>$("#menuAbout").addClass("navi-active");</script>
<div class="contentBody">
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:TextBox ID="tb_Test" EnableViewState="true" CausesValidation="false" runat="server"></asp:TextBox>
<asp:LinkButton ID="btn_Test" runat="server" OnClick="btn_Test_Click" Text="send test" />
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btn_Test" EventName="click" />
</Triggers>
</asp:UpdatePanel>
</div>
</asp:Content>
public partial class About : Page
{
protected void Page_Load(object sender, EventArgs e)
{
this.Page.Master.EnableViewState = true;
if (IsPostBack)
{
var test_var = tb_Test.Text; //returning empty
}
}
protected void btn_Test_Click(object sender, EventArgs e)
{
var test_var = tb_Test.Text; //returning empty
}
}
UPDATE:
site.master.cs
public partial class SiteMaster : MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindCategories();
}
}
protected void BindCategories()
{
Categories Categories = new Categories();
rpt_categories.DataSource = Categories.Get_Categories();
rpt_categories.DataBind();
}
protected void lb_newsCat_Command1(object sender, CommandEventArgs e)
{
switch (e.CommandName)
{
case "naviTo":
//Redirect user to selected category
Response.Redirect("~/" + e.CommandArgument.ToString());
break;
}
}
}
I'm converting a PHP website to an ASP.net website. Turns out I had another HTML form tag on a search box that I haven't started working on yet.
Unfortunately the debugger doesn't throw an error if you have another form tag so anybody else who's just spent hours of their lives searching, double check you don't have more than 1 form tag!
In my site.master.aspx file, I had a search box as follows:
<form method="post" action="?">
<input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-primary my-2 my-sm-0" type="submit">Search</button>
</form>
Once I took the extra form tag out, everything worked fine.

persist ddl values and selected value in between postbacks

I have a save button and a drop down list on a page. Inside the page Load, the drop down list is populated if !Page.PostBack (AutoPostBack=false). So, the first time I load the page, the drop down list is populated. I also have a save method to go with the save button. When this button is clicked, it should do something with the selected value of the drop down list. My problem is that the drop down list has no value (is null) inside the button save method. How would you fix this?
Markup:
MyClass.aspx
<%# Page Language="C#" AutoEventWireup="true" Inherits="MyClass" %>
<asp:Content ID="Content3" ContentPlaceHolderID="MainRegion" runat="server">
<div>
<asp:DropDownList ID="myDdl" runat="server" OnSelectedIndexChanged="myDdlChange" ViewStateMode="Enabled" EnableViewState="true" />
</div>
<br />
<div style="min-width: 300px; max-width: 770px;">
<asp:TextBox id="txtBox" runat="server" TextMode="MultiLine" />
</div>
<div class="buttonContainer">
<span >
<asp:Button ID="btnSave" runat="server" Text="Save" onclick="btnSave_Click" />
</span>
</div>
</asp:Content>
Then, in the code behind:
MyClass.aspx.cs
public class MyClass
{
protected global::System.Web.UI.WebControls.DropDownList myDdl;
protected global::System.Web.UI.WebControls.TextBox txtBox;
protected global::System.Web.UI.WebControls.Button btnSave;
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
if (this.Page.IsPostBack)
Session["selectedID"] = myDdl.SelectedValue; // my attempt to put the selected value from ddl in a session var, to use it later inside the save method but it didn't work
if (!Page.IsPostBack)
{
//create array1 here
myDdl.Items.Clear();
myDdl.Items.AddRange(array1);
Session["selectedID"] = myDdl.SelectedValue;
myDdlChange(null, null);
this.DataBind();
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
//do something based on myDdl.SelectedValue (which shouldn't be null)
}
protected void myDdlChange(object source, EventArgs e)
{
txtBox.Text = myDdl.SelectedValue;
}
}
}
I think the main problem is you should be using Page_Load instead of OnLoad.
You don't need to use Session to remember the SelectedValue.
Try something like this which works for me...
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
PopulateDropdown();
}
private void PopulateDropdown()
{
myDdl.Items.Clear();
var array1 = new ListItem[3];
array1[0] = new ListItem("item1", "item1");
array1[1] = new ListItem("item2", "item2");
array1[2] = new ListItem("item3", "item3");
myDdl.Items.AddRange(array1);
myDdl.DataBind();
}
protected void btnSave_Click(object sender, EventArgs e)
{
var selectedVal = myDdl.SelectedValue; // putting a breakpoint here shows myDdl.SelectedValue is not null
}
protected void myDdlChange(object sender, EventArgs e)
{
}

Setting Session Variables when image buttons are clicked?

I have two image buttons on the page. When either is clicked it needs to set the session variables yesID and NoId before the page is posted back. I tried putting the code in the click events for each button but the page loads again before it runs that code in the click events. How can i set the 2 session variables when either image is clicked?
<div id="MainPics">
<div id="RightPic">
<p>
<asp:Label ID="FirstPicMemberNameLabel" runat="server" Text="" Font-Bold="True" ForeColor="White"></asp:Label>
</p>
<asp:ImageButton ID="FirstPicLink" Width="90%" runat="server"
onclick="FirstPicLink_Click" />
</div>
<div id="LeftPic">
<p>
<asp:Label ID="SecondPicMemberNameLabel" runat="server" Text="" ForeColor="White" Font-Bold="True"></asp:Label>
</p>
<asp:ImageButton ID="SecondPicLink" Width="90%" runat="server"
onclick="SecondPicLink_Click" />
</div>
<div id="skip">
<asp:LinkButton ID="LBNoChoice" PostBackUrl="~/default.aspx" ForeColor="White" runat="server">Skip - I Can't Choose</asp:LinkButton>
</div>
</div>
Code Behind Page
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Session["yesID"] = 0;
Session["noId"] = 0;
}
else
{
//Send Session Variables to Database for Storage.
}
}
protected void FirstPicLink_Click(object sender, ImageClickEventArgs e)
{
Session["yesID"] = 1;
Session["noId"] = 2;
}
protected void SecondPicLink_Click(object sender, ImageClickEventArgs e)
{
Session["yesID"] =2;
Session["noId"] = 1;
}
Does this logic help?
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Session["yesID"] = 0;
Session["noId"] = 0;
}
//else
//{
//Send Session Variables to Database for Storage.
//}
}
protected void FirstPicLink_Click(object sender, ImageClickEventArgs e)
{
Session["yesID"] = 1;
Session["noId"] = 2;
SendSessionVariables(Session["yesID"], Session["noId"]);
}
private void SendSessionVariables(object p, object p_2)
{
// Your database code here
}
protected void SecondPicLink_Click(object sender, ImageClickEventArgs e)
{
Session["yesID"] = 2;
Session["noId"] = 1;
SendSessionVariables(Session["yesID"], Session["noId"]);
}
When you click on the asp.net image button, It usually fires the click event and calls the method if autopostback is not disabled. If you really want to change the session values before the autopostback being hit, Invoke a client side javascript function on the onclientclick event and from that, make an ajax call to a server page where you update the session variable values. Once you get the response from the ajax call (success event) , return true so that the web page continues with the form post back event.

Categories