Redirect to page on button click - c#

Hi I am trying to redirect to the previous page on button click but things are not going so well here is my code:
private string previousPage = string.Empty;
protected void Page_Load(object sender, EventArgs e)
{
if( Request.UrlReferrer != null)
{
previousPage = Request.UrlReferrer.ToString();
CrossSideScriptingErrorCheck.Text = previousPage;
}
}
protected void BackButton_Click( object sender , EventArgs e )
{
Response.Redirect(previousPage);
}
When I first get directed to this page the previousPage variable stores the correct URL but after I click on the button for some reason previousPage value is change to the curent page url and i get sent back to the curent page.
What am I doing wrong here and how can I corect it?
EDIT
I wrapped the code like this:
if(!IsPostBack)
{
if( Request.UrlReferrer != null ) {
previousPage = Request.UrlReferrer.ToString();
CrossSideScriptingErrorCheck.Text = previousPage;
}
}
And I get redirected to a page that I did not create and has a link.On the page is written:
Object moved to here.
"here" is a link and when I cliked it I get sent back to the page I pressed the button

When you have a postback, the referrer is the page itself, so this is expected behaviour :-)
One solution would be to have something like this:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack) Session["prev"] = Request.UrlReferrer.ToString();
if(Session["prev"] == null) {some code that disables the back button goes here!}
}
protected void BackButton_Click( object sender , EventArgs e )
{
Response.Redirect(Session["prev"] as string);
}
The reason why this answer works and the others posted so far do not, is that I am using Session["prev"] to remember the most recent valid referrer. So the trick is to 1) realise that when you have a postback the referer is url of the page itself (which the OP did) and 2) remember the last non-post referrer URL so that you can use it when the Back button is pressed.

You need to test for a postback. When you click the button the page is posted back to the server and the referrer becomes the page you are on and the value you want is overwritten.
private string previousPage = string.Empty;
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
if( Request.UrlReferrer != null)
{
previousPage = Request.UrlReferrer.ToString();
CrossSideScriptingErrorCheck.Text = previousPage;
}
}
}
protected void BackButton_Click( object sender , EventArgs e )
{
Response.Redirect(previousPage);
}

you forgot put it in IsPostBack that y its working like this
if(!IsPostBack)
{
if( Request.UrlReferrer != null)
{
previousPage = Request.UrlReferrer.ToString();
CrossSideScriptingErrorCheck.Text = previousPage;
}
}
code like this to work with it...

When you click on your button, the page load is executed before the click event, so it is resetting the value of your previousPage variable. You need to wrap it in a check to make sure it's not been posted back, like so:
if (!IsPostBack) {
previousPage = Request.UrlReferrer.ToString();
}

I am the last to answer but was first to comment
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
if( Request.UrlReferrer != null)
{
previousPage = Request.UrlReferrer.ToString();
CrossSideScriptingErrorCheck.Text = previousPage;
}
}
}

Related

Increment variable on page postback and load different pages

I have a property as shown below
private int Step
{
get { return (int)Session["step"]; }
set { Session["step"] = value; }
}
In the Page_Init method, I am initializing it as below
protected void Page_Init(object sender, EventArgs e)
{
if (!IsPostBack)
{
Step = 0;
}
}
In the click event of my save button, I am trying to reload the page as if it was the first time the save button was clicked. If it was the second time the save button was clicked, then redirect to another page.
protected override void cmdNext_Click(object sender, EventArgs args)
{
this.SaveViewModel();
Step++;
if (Step > 1)
{
base.cmdNext_Click(sender, args);
}
else
{
Response.Redirect(Request.RawUrl); //reloading the page again
}
}
The issue is that on the first time the page is reloaded and the Page_Init method sets the variable to 0 again so it never goes past through 1. Can someone please tell me how I can load the same page on the first button click and move on to some other page after the second button click?
Thanks
You can simply check if the Session is null before initializing
protected void Page_Init(object sender, EventArgs e)
{
if (!IsPostBack && Session["step"] == null)
{ Step = 0; }
}

How to destroy query string after redirecting from one page to another page on page load event?

I am having 2 pages name as :
Abc.aspx
pqr.aspx
Now on page load of Abc.aspx i am doing this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (!string.IsNullOrEmpty(Request.QueryString["Alert"]))
{
if (Request.QueryString["Alert"] == "y")
{
//Here on redirection from Pqr.aspx i will display Javascript alert that your "Your data save"
}
}
else
{
//Dont do anything
}
}
}
Now from pqr.aspx page i am redirecting to Abc.aspx and passing query string on button click:
protected void Save_Click(object sender, EventArgs e)
{
//saving my data to database.
Response.Redirect("~/Abc.aspx?Alert=yes");
}
But what is happening is if anybody enters url like this in browser then still this alert is coming:
http://localhost:19078/Abc.aspx?Alert=yes
Then still this javascript alert box comes.
What i want is after redirecting from my Pqr.aspx page only this alert should come.
How to do this??
In Asp.net there is an object named Request.UrlReferrer.With this property you can get the previous page from which you come to the current page
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (!string.IsNullOrEmpty(Request.QueryString["Alert"]))
{
if (Request.QueryString["Alert"] == "y" && Request.UrlReferrer != null && Request.UrlReferrer.LocalPath == "/pqr.aspx") // if the root is same
{
//Here on redirection from Pqr.aspx i will display Javascript alert that your "Your data save"
}
else
{
//Dont do anything
}
}
}
}

Intercept button click on page load

I need to write a code that can intercept a click of some button (asp button) than execute some code, and if a method return true, call the original click.
So the points are:
1- I don´t know how to save the original click.
2- Identify the button that was clicked.
Ex:
protected void Page_Load(object sender, EventArgs e)
{
var b = getButtonThatWasClicked();
var originalClick = b.Click;
if(callSomeMethod(b))
originalClick(null,null);
}
EDIT:
Ok managed to get the button who made the click doing this...Now i need to prevent the original Click to get called. The method bellow didn't worked. Even overriding the original click to a new Handler the old Handler got called and executed. I thing ASP.NET read it and make something like a call stack of events to get called.Even if the handler change the old still in the stack.
public void ButtonsTestMethod()
{
var listOfButtons = listaDeBotes.Where(b => b.CommandName != "");
foreach (var button in listOfButtons)
{
if (Request.Form[button.UniqueID] != null)
{
var buttonFromRequest = Request.Form[button.UniqueID];
if (buttonFromRequest == null)
continue;
if (button.CommandName != "xxx")
{
//validate things
//if(TemPermissao(Tela,GetAcaoDoBotao(botao.CommandName)))
//if(!canexecuteSomething())
button.Click += new EventHandler(defaultClick);
}
}
}
}
void defaultClick(object sender, EventArgs e)
{
//show error
}
protected void Page_Load(object sender, EventArgs e)
{
//other code
ButtonsTestMethod();
}
I don´t know if its possible but would appreciate some help =/
Thanks.
To get the control name, you can try the following in the page load:
protected void Page_Load(object sender, EventArgs e)
{
if( IsPostBack )
{
string senderControl = Request.Params["__EVENTTARGET"].ToString();
//senderControl will contain the name of the button/control responsible for PostBack
}
}
The first argument in the button click event handler is the sender. You can cast that sender as a Button object and then you should be able to identify which button that was based on that object. That way, you can eliminate having that function to figure out which is clicked.
void GreetingBtn_Click(Object sender, EventArgs e)
{
Button clickedButton = (Button)sender;
if(clickedButton.Text == "bla")
{
//Do stuff
}
}

asp.net cookie not saved

Can you please tell me what am I doing wrong here.
Why the Cookie data is not stored when I reload the page:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// it is always null !!!!
if (Response.Cookies["user_id"].Value != null)
{
//code never gets here
}
}
}
and this is the code for storing the cookie (after clicking a checkbox):
protected void CheckBoxRememberMe_Click(object sender, EventArgs e)
{
Response.Cookies["user_id"].Value = tbUserID.Text;
Response.Cookies["user_id"].Expires = DateTime.Now.AddDays(15);
}
So: I click on the checkbox, the value of tbUserID textbox is stored in the HttpCookie, then I reload the page (refresh) and the value is null.
Any idea ?
When checking for the cookie you want to be making a request rather than adding the cookie to the response.
if (Request.Cookies["user_id"].Value != null)
{
//code should get here
}

Getting Session Value in Master Page - PageLoad

I have a master page on which I have a dropdown of Language. I save dropdown's selected value in session. and want to check on page load that what's the value in session. But it gives exception because on page load, there is nothing in session.
Can anyone tell me what method should I call before page load in which I can set session to a default value?
Thanks in advance.
protected void ddlLanguage_SelectedIndexChanged(object sender, EventArgs e)
{
Session["Language"] = ddlLanguage.SelectedValue;
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ddlLanguage.SelectedValue = Session["Language"].ToString();
}
You could initialize your session variable to a default value inside the Page_Init event. So by the time the Page_Load event is fired, at least you would have a value to check against.
Alternatively, you could just check the Session variable for a null value in the Page_Load event & not try and use its value if indeed it is null.
For this second option, change your code to be something like:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ddlLanguage.SelectedValue = Session["Language"] == null ? "0" : Session["Language"].ToString();
}
Replace the zero in the true condition of the ternary operator with whatever default value you have in your dropdown list.
You have to check it before using it because when you are trying to get the value from the session it is null and not assigned any value yet.
if (Session["Language"] != null)
{
ddlLanguage.SelectedValue = Session["Language"].ToString();
}
No need to set default option in page init event, you can set language dropdown in page load event also like this ways :
Master page Code
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Session["culture"] != null)
ddlLanguage.SelectedValue = Session["culture"].ToString();
else
{
ddlLanguage.SelectedValue = "en-US";
Session["culture"] = "en-US";
}
}
}
protected void ddlLanguage_SelectedIndexChanged(object sender, EventArgs e)
{
Session["culture"] = ddlLanguage.SelectedValue;
}
=================
By this way I can preserve selected language in session and can use in whole application.
You could use Page_PreLoad event to set your session variable's value...

Categories