Session variables set - Page_Load method C# - c#

I tried to link default1.aspx and default 2.aspx.
What I'm trying to do is to display calculated results in default1.aspx when clicking confirm button in default2.aspx.
I run the codes but it doesn't work really.
How can I fix this?
I wrote the codes in default1.aspx below:
protected void confirmBookingButton_Click(object sender, ImageClickEventArgs e)
{
Response.Redirect("RoomBookingMain.aspx");
Session["confirmBooking"] = "confirm";
Session["totalBooking"] = calculateTextBox.Text;
}
and then I wrote other codes in default2.aspx like:
public partial class RoomBookingMain : System.Web.UI.Page
{
static int nbBookingInt = 0;
static int totalRevenueInt = 0;
}
protected void Page_Load(object sender, EventArgs e)
{
bookingNbLabel.Text = nbBookingInt.ToString();
totRevenueLabel.Text = totalRevenueInt.ToString();
string confirmBooking = (string)(Session["confirmBooking"]);
if ((string)(Session["confirmBooking"]) == "confirm")
{
nbBookingInt += 1;
totalRevenueInt += int.Parse(Session["totalBooking"].ToString());
Session["confirmBooking"] = "no current booking";
}
}

Session["confirmBooking"] = "confirm";
Session["totalBooking"] = calculateTextBox.Text;
Response.Redirect("RoomBookingMain.aspx");
Assign Session before Response.Redirect(). Redirect method will stop the execution at that point.
If you need to pass the data only to next page and if no secure data is involved you can use QueryStrings.

Related

dropdown list goes back to first value after selected index changes

I have a drop down list with a button event that should send it's value for a textbox.But,even if I choose a value that is not the first one in the DDL,it only sends the value of the first item in the DDL. I was told to add the !IsPostBack in the page load,but it didn't help.
Codes:
protected void Page_Load(object sender, EventArgs e)
{
string testeddl;
codProfessor = Request.QueryString["id"];
if (db.conecta())
{
ddlTeste.Items.Clear();
ddlTesteAltDel.Items.Clear();
ddlQuestoes.Items.Clear();
listaX = db.retornaTestes(codProfessor);
for (int i = 0; i < listaX.Count; i++)
{
testeddl = listaX[i].nometeste;
ddlTesteAltDel.Items.Add(testeddl);
}
protected void btnBuscarTeste_Click(object sender, EventArgs e)
{
if (db.conecta())
{
int posic = ddlTesteAltDel.SelectedIndex;
txtNomeTeste.Text = listaX[posic].nometeste;
ddlaltdelTeste.Text = listaX[posic].materiateste;
}
}
}
}
In Page_Load, just need to indicate:
if(!IsPostBack()
{
// rest of the code.
}

Defining and adding value to variable from session-variable

I'm trying to make a script that checks, if a user has the right age before joining a team. If the user age doesn't match the team age, the script should stop at this page, and require the user to click the button "BackToLastPageBtn" go back to the previous page, which uses a variable called "BackToLastPage", which gets its value from 'Session["currentUrl"]', before it is reset at Page_load.
The problem is, that it tells me the value is null, when clicking the button.
I don't know why it is null, when i add the value to "BackToLastPage", BEFORE resetting Session["currentUrl"]. I hope someone can tell me, and guide me in the right direction.
The CodeBehind - script
public partial class JoinTeam : System.Web.UI.Page
{
//Defining Go back variable
private string BackToLastPage;
protected void Page_Load(object sender, EventArgs e)
{
int BrugerId = Convert.ToInt32(Session["BrugerId"]);
int TeamId = Convert.ToInt32(Request.QueryString["HoldId"]);
//Adding value to go back variable from sessionurl
BackToLastPage = (string)Session["CurrentUrl"];
//Resets sessionurl.
Session["CurrentUrl"] = null;
if (Session["brugerId"] != null)
{
if (ClassSheet.CheckIfUserAgeMatchTeamAge(BrugerId, TeamId))
{
ClassSheet.JoinATeam(BrugerId, TeamId);
if (BackToLastPage != null)
{
//Uses the new savedUrl variable to go back to last page.
Response.Redirect(BackToLastPage);
}
else
{
Response.Redirect("Default.aspx");
}
}
else
{
AgeNotOk.Text = "Du har ikke den rigtige alder til dette hold";
}
}
else
{
//Not saving last page. Need to find solution.
Response.Redirect("Login.aspx");
}
}
//NOT WORKING...
protected void BackToLastPageBtn_Click(object sender, EventArgs e)
{
//Go back button
//Response.Write(BackToLastPage);
Response.Redirect(BackToLastPage);
}
}
Since you are setting session["CurrentURL"] to null in page_load. When the event is fired it no longer exists. Below is code that i got it working. I had to cut some of your code out since i dont have the definition of all your classes. Private properties do not persist through postbacks. If you wanted it to work the way you have it, you should save the previoius url in a hidden field on the page itself.
Page One:
protected void Page_Load(object sender, EventArgs e)
{
Session["CurrentUrl"] = Request.Url.ToString();
Response.Redirect("~/SecondPage.aspx");
}
Page Two:
private string BackToLastPage { get { return (Session["CurrentUrl"] == null) ? "" : Session["CurrentUrl"].ToString(); } }
protected void Page_Load(object sender, EventArgs e)
{
int BrugerId = Convert.ToInt32(Session["BrugerId"]);
int TeamId = Convert.ToInt32(Request.QueryString["HoldId"]);
if (Session["brugerId"] != null)
{
//CUT CODE OUT DONT HAVE YOUR DEFINITIONS
Response.Write("brugerid was not null");
}
}
protected void BackToLastPageBtn_Click(object sender, EventArgs e)
{
//YOU SHOULD SET THE CURRENT URL TO NULL HERE.
string tempUrl = BackToLastPage;
Session["CurrentUrl"] = null;
Response.Redirect(tempUrl);
}
You can also try this, Store the return url in a hiddenfield and only set it if it is not a page postback:
Markup HTML:
<form id="form1" runat="server">
<div>
<asp:Button ID="btnOne" runat="server" OnClick="BackToLastPageBtn_Click" Text="Button One" />
<asp:HiddenField ID="hfPreviousUrl" runat="server" />
</div>
</form>
Code Behind:
private string BackToLastPage //THIS WILL NOW PERSIST POSTBACKS
{
get { return hfPreviousUrl.Value; }
set { hfPreviousUrl.Value = value;}
}
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)//THIS PREVENTS THE VALUE FROM BEING RESET ON BUTTON CLICK
BackToLastPage = (string)Session["CurrentUrl"];
int BrugerId = Convert.ToInt32(Session["BrugerId"]);
int TeamId = Convert.ToInt32(Request.QueryString["HoldId"]);
//Resets sessionurl.
Session["CurrentUrl"] = null;
if (Session["brugerId"] != null)
{
Response.Write("brugerID was not null");
}
else
{
//REMOVED FOR TEST PURPOSES
//Response.Redirect("Login.aspx");
}
}
protected void BackToLastPageBtn_Click(object sender, EventArgs e)
{
Response.Redirect(BackToLastPage);
}

Creating hit counter for website

I am creating a website having a masterpage. I want to create a hit counter to record the number of visitor and i found a code and put it in my masterpage. The code is as:
Markup Code:
<%# Control Language="C#" AutoEventWireup="true" CodeFile="counter.ascx.cs" Inherits="counter" %>
<asp:Label ID="lblCounter" runat="server"></asp:Label>
Code Behind - C#:
protected void Page_Load(object sender, EventArgs e)
{
this.countMe();
DataSet tmpDs = new DataSet();
tmpDs.ReadXml(Server.MapPath("~/counter.xml"));
lblCounter.Text = tmpDs.Tables[0].Rows[0]["hits"].ToString();
}
private void countMe()
{
DataSet tmpDs = new DataSet();
tmpDs.ReadXml(Server.MapPath("~/counter.xml"));
int hits = Int32.Parse(tmpDs.Tables[0].Rows[0]["hits"].ToString());
hits += 1;
tmpDs.Tables[0].Rows[0]["hits"] = hits.ToString();
tmpDs.WriteXml(Server.MapPath("~/counter.xml"));
}
An xml file in the root directory to make the code work. The XML file is as:
<?xml version="1.0" encoding="utf-8" ?>
<counter>
<count>
<hits>0</hits>
</count>
</counter>
But every pages within my website triggers the counter whenever i visit them. Please help me modify this code to trigger the counter only one time by one visitor.
I have decided to put the code on index page only, but still every refresh and every lick to open the index (even while staying on index page) triggers the counter.
Why not just add a session? I think it's the easiest way for an XML solution, if you saved it to SQL you could have more logic involved.
private void countMe()
{
if(Session["Counted"]==null){
DataSet tmpDs = new DataSet();
tmpDs.ReadXml(Server.MapPath("~/counter.xml"));
int hits = Int32.Parse(tmpDs.Tables[0].Rows[0]["hits"].ToString());
hits += 1;
tmpDs.Tables[0].Rows[0]["hits"] = hits.ToString();
tmpDs.WriteXml(Server.MapPath("~/counter.xml"));
Session["Counted"] = "Yes";
}
}
You need to check the url of the page for the counter to hit the code. Try something like this
protected void Page_Load(object sender, EventArgs e)
{
string url = HttpContext.Current.Request.Url.AbsoluteUri;
if(url.Contains("index.aspx")
{
this.countMe();
}
DataSet tmpDs = new DataSet();
tmpDs.ReadXml(Server.MapPath("~/counter.xml"));
lblCounter.Text = tmpDs.Tables[0].Rows[0]["hits"].ToString();
}
You can get the solution from Global.ascx File.
Go to code behind of Golobal.ascx.cs in your application.
Declare a variable in Global.Cs File.
And Maintain a Count in 'Session_Start' Function Of Global.ascx.cs file;
write some public method to get user count
Eg:
protected void Session_Start(Object sender, EventArgs e)
{
totalNumberOfUsers += 1;
currentNumberOfUsers += 1;
}
protected void Session_End(Object sender, EventArgs e)
{
currentNumberOfUsers -= 1;
}
public static int TotalNumberOfUsers
{
get
{
return totalNumberOfUsers;
}
}
public static int CurrentNumberOfUsers
{
get
{
return currentNumberOfUsers;
}
}
In addition to using "Session" as in prospectors example, due to the possibility of synchronization issues , don't forget to lock the DataSet before use.
private static readonly object LockObj = new object();
private static DataSet dataSet = new DataSet();
protected void Page_Load(object sender, EventArgs e)
{
if (Session["Counted"] == null)
{
lock (LockObj)
{
dataSet.ReadXml(Server.MapPath("~/counter.xml"));
dataSet.Tables[0].Rows[0]["hits"] = (1 + int.Parse(dataSet.Tables[0].Rows[0]["hits"].ToString())).ToString();
dataSet.WriteXml(Server.MapPath("~/counter.xml"));
dataset.clear();
}
Session["Counted"] = "true";
}
}

Dynamically created LinkButton posts back but does not call onClick Method

My issue is the page posts back but does not call the method.
Here is where I create the link Buttons inside the RenderProducts method
for (var counter = 1; counter <= numberOfPages; counter++)
{
var pagingLink = new LinkButton
{
Text = " " + counter.ToString(CultureInfo.InvariantCulture) + " ",
ID = "page" + counter
};
pagingLink.Attributes["runAt"] = "server";
pagingLink.Attributes["class"] = "paging-link";
pagingLink.Attributes.Add("AutoPostBack", "true");
pagingLink.Attributes.Add("AutoEventWireup", "true");
pagingLink.Click +=ChangePage;
paging.Controls.Add(pagingLink);
}
The method it is calling
public void ChangePage(object sender, EventArgs args)
{
// handle this particular case
RenderProducts(2);
}
For completeness below you will see on PostBack I prevent it's default action
protected void Page_Load(object sender, EventArgs e)
{
GetSideBar();
BuildRefineSearch();
PopulateList();
PerformSearch();
if(!IsPostBack )
{
RenderProducts(1);
}
}
I moved everything to the
override protected void OnInit(EventArgs e)
as this was a user control this solved my issue.
Thanks to Chandermani for getting me to think about when my event was firing.

DropDownList SelectedValue doesn't Change

In my page when I call searchBtn_Click the selectedvalue will be carried into the variable ind only if the selection hasnt changed. So if a User selects Automotive, then clicks the search button, and then they change the selection to Government, it will refresh the page and display Automotive, am I missing something in the postback or doing something wrong here?
protected void Page_Load(object sender, EventArgs e)
{
string industry = "";
if (Request.QueryString["ind"] != null)
{
industry = Request.QueryString["ind"].ToString();
if (industry != "")
{
indLabel.Text = "Industry: " + industry;
IndustryDropDownList.SelectedValue = industry;
}
}
}
protected void searchBtn_Click(object sender, EventArgs e)
{
string ind = IndustryDropDownList.SelectedValue;
Response.Redirect("Default.aspx?ind=" + ind);
}
Simply replace your code with this code
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
string industry = "";
if (Request.QueryString["ind"] != null)
{
industry = Request.QueryString["ind"].ToString();
if (industry != "")
{
indLabel.Text = "Industry: " + industry;
IndustryDropDownList.SelectedValue = industry;
}
}
}
}
You don't need to use Redirect and QueryString.
Use SelectedValue at Page_PreRender (In your sample clear Page_Load completely).
you better try this in search button click
but remember your dropdowndlist's value-member==display-member to do this.. i had the same problem and this is how i solved it.
string ind = IndustryDropDownList.Text.Tostring().Trim();
Response.Redirect("Default.aspx?ind=" + ind);
i knw this is not the best way but it did work for me..
You're not leveraging the ViewState of asp.net forms (good mentality for MVC 3 though). But since you are using asp.net, you should change your code to this:
The logic in your page load is not necessary, unless you want the user to set the industry as the enter the page. Since I assumed you do, I left some logic in there. It checks for postback because it doesn't need to execute after the initial page load.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack() && Request.QueryString["ind"] != null)
{
SetIndustry(Request.QueryString["ind"].ToString());
}
}
protected void SetIndustry(String industry)
{
indLabel.Text = "Industry: " + industry;
IndustryDropDownList.SelectedValue = industry;
}
You don't have to redirect the page, since Page_Load will be called every time the page posts back. With .NET, your controls remember their last values automatically.
protected void searchBtn_Click(object sender, EventArgs e)
{
SetIndustry(IndustryDropDownList.SelectedValue);
}

Categories

Resources