I am working on a C# project using asp framework 4.5 and I am having this problem :
I want a way to avoid a resubmission of the form on page refresh (without self redirect):
When refreshing the page, the button does trigger itself, I need to avoid the second submission without page redirection .
I am trying to upload a file, on the first try every thing is Working fine, but, when I hit f5 to refresh the page, the form will be resubmitted.
try below code
public bool IsPageRefresh = false;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ViewState["postids"] = System.Guid.NewGuid().ToString();
Session["postid"] = ViewState["postids"].ToString();
}
else
{
if (ViewState["postids"].ToString() != Session["postid"].ToString())
{
IsPageRefresh = true;
}
Session["postid"] = System.Guid.NewGuid().ToString();
ViewState["postids"] = Session["postid"].ToString();
}
}
just check below condition on button click
if (!IsPageRefresh)
{
// write you post code
}
try this it's working perfect for me .
Related
I have two pages MainPage.aspx and ChildPage.aspx. From main page when i click a button i redirect to ChildPage.
If i give the address of ChildPage directly on browser, i do not want to load it directly instead i want to redirect to MainPage.
the ChildPage must be loaded only if it is loaded from the MainPage.
How do I find from where the ChildPage.aspx is loaded. how to find the parent page of it or from where it is loaded.
can we try something in the below code
if (!IsPostBack)
{
if (finding_source)
{
Response.Redirect("MainPage.aspx");
}
}
You can use Request.UrlReferrer.AbsolutePath to see the previous page.
if (!IsPostBack)
{
if (Request.UrlReferrer != null && Request.UrlReferrer.AbsolutePath == "/MainPage")
{
//do what you want
}else{
Response.Redirect("~/MainPage.aspx");
}
}
TIP But be careful with using it with postbacks since it will change the value of Request.UrlReferrer to the current page during a postback.
Even though your question is not clear , here i am trying to give my solution.
MAINPAGE.ASPX BUtton Click
protected void lnkRegister_Click(object sender, EventArgs e)
{
Session["MainPage"] = "true";//Encrypt it if u wish
Response.Redirect("childpage.aspx");
}
CHILDPAGE.ASPX PAGE LOAD
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (!string.IsNullOrEmpty(Session["MainPage"] as string) && Session["MainPage"].Tostring()=="true")
{
//proceed
}
else
{
Response.Redirect("mainpage.aspx");
}
}
GLOBAL.ASAX
void Application_End(object sender, EventArgs e)
{
// Code that runs on application shutdown
Session.RemoveAll();
Session.Clear();
Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
Response.Cache.SetValidUntilExpires(false);
Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetNoStore();
}
it is little difficult to control browser shutdown or close...but you can workaround global asax file when your application shutsdown.
In codebehind of my asp.net page has a button and when single-click her open a RadWindow, don't have a problem.
The problem is when somebody close the radwindows, because to open is necessary double-click. I don't like this.
For me control refresh to disable the double-click page I use:
Boolean IsPageRefresh;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ViewState["postids"] = System.Guid.NewGuid().ToString();
Session["postid"] = ViewState["postids"].ToString();
}
else
{
if (ViewState["postids"].ToString() != Session["postid"].ToString())
{
IsPageRefresh = true;
}
Session["postid"] = System.Guid.NewGuid().ToString();
ViewState["postids"] = Session["postid"].ToString();
}
}
But don't work, somebody use F5 or click in button the radwindow open again.
How can I detect to difference when use F5 and Click button?
I am developing a Web app for conducting a Online examination. I want to stop the contestants from refreshing the page in the browser. If they do I want to navigate them to a page which says they are disqualified. How can I implement this?
The following code snippet detects 'Refresh' in page_load function
bool IsPageRefresh = false;
protected void Page_Load(object sender, EventArgs e)
{
//this section of code checks if the page postback is due to genuine submit by user or by pressing "refresh"
if (!IsPostBack)
{
ViewState["ViewStateId"] = System.Guid.NewGuid().ToString();
Session["SessionId"] = ViewState["ViewStateId"].ToString();
}
else
{
if (ViewState["ViewStateId"].ToString() != Session["SessionId"].ToString())
{
IsPageRefresh = true;
}
Session["SessionId"] = System.Guid.NewGuid().ToString();
ViewState["ViewStateId"] = Session["SessionId"].ToString();
}
}
You can then use the 'IsPageRefresh' boolean flag in the code-behind to determine if it's a postback due to genuine User submit action or by browser 'Refresh'.
I try to create a web application that got a button that change an image. this is my code:
public partial class _Default : System.Web.UI.Page
{
private bool test ;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
if (test)
{
Image1.ImageUrl = #"~/images/il_570xN.183385863.jpg";
test = false;
}else
{
Image1.ImageUrl = #"~/images/BAG.png";
test = true;
}
}
}
my problem is that the page reload every time. meaning, after i click the button "test" return to it's initial value. how can i have a variable that i can access all through the session?
please notice, i don't want to solve this specific image problem, but to know how to keep data until the user closed the page.
You can store arbitrary values in Session
Session["someKey1"] = "My Special Value";
Session["someKey2"] = 34;
Or more complex values:
Session["myObjKey"] = new MyAwesomeObject();
And to get them back out:
var myStr = Session["someKey1"] as String;
var myInt = Session["someKey2"] as Int32?;
var myObj = Session["myObjKey"] as MyAwesomeObject;
ASP.NET webforms are stateless so this is by design.
you can store your bool variable in the ViewState of the page so you will always have it updated and persisted within the same page.
Session would also work but I would put this local page related variable in the ViewState as it will be used only in this page ( I guess )
Store the variable in a cookie! :)
Example:
var yourCookie = new HttpCookie("test", true);
Response.Cookies.Add(yourCookie);
Session["show_image"] = "true";
To achieve what you want you need to check if is PostBack or not as so:
protected void Button1_Click(object sender, EventArgs e)
{
if (test && !IsPostBack)
{
Image1.ImageUrl = #"~/images/il_570xN.183385863.jpg";
test = false;
}else
{
Image1.ImageUrl = #"~/images/BAG.png";
test = true;
}
}
BUT, don't do it that way. You are approaching this wrong. You wouldn't want to store in Session things like whether this image is shown or not, etc. It's difficult to suggest an approach without knowing the specific issue you are facing.
Another option than the already mentioned would be to store the data in the ViewState. If it's just used in postback situations, that might be a possible way.
ViewState["test"] = true;
You save memory on the server but use a little bit of bandwith. The data gets lost, when the user browses to another page.
I have a problem with a webform.
My Goal: Intially when a page is loading, it has to load every textbox empty. After filling the info and click submit, it has to get submitted(UpdatePaymentInfo())
Problem: Here, When the user fills the info and clicks Submit,it calls onload function even before the submit button and makes all text box empty.
Here is the code:
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
string QueryStringupdatecreditcard1 = Request.QueryString.ToString();
if (String.Equals(QueryStringupdatecreditcard1, "tabID=B"))
{
divTitle.Visible = false;
trmain.Visible = false;
tdOrderSummary.Visible = false;
trCCandBilling.Visible = true;
trtest2.Visible = false;
divUpdatecreditcard.Visible = true;
trusecompaddress.Visible = false;
txtFirstName.Text = "";
txtLastName.Text = "";
txtAddress1.Text = "";
txtAddress2.Text = "";
txtCity.Text = "";
txtZip.Text = "";
txtCardNo.Text = "";
txtVccNumber.Text = "";
trAmountCharged.Visible = false;
}
}
protected void imgbtnSubmit_Click(object sender, ImageClickEventArgs e)
{
try
{
UpdatePaymentInfo();
}
}
Wrap the current contents of your OnLoad method in:
if (!Page.IsPostBack)
{
// Code in here will only be executed when the page is *not* being loaded by a postback
}
This is because, as per the ASP.NET Page Life Cyle, the things that you care about in this instance happen in this order:
Load - During load, if the current request is a postback, control
properties are loaded with information
recovered from view state and control
state.
Postback event handling - If the request is a postback, control event
handlers are called. After that, the
Validate method of all validator
controls is called, which sets the
IsValid property of individual
validator controls and of the page.
So what happens is (somewhat simplified):
You click the image button, triggering the postback.
The data from your form is loaded into your controls.
Your OnLoad method overwrites the values in the controls to clear them.
Your click handler is run, but because of step 3 it sees empty values.
As others have sort-of mentioned, it wouldn't necessarily be a bad thing to refactor your OnLoad method whilst you're doing this. At the moment you seem to have it doing two distinct things:
Clearing the text fields
Setting the visibility of fields
It might be worth separating this into one or two (depending on if the visibility setting and field clearing will be done independently) separate methods and adjusting your OnLoad method so it looks like this:
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
if (!Page.IsInPostBack)
{
SetFieldVisibility();
ClearFields();
}
}
Page_Load always occurs.
See the documentation on the Page Lifecycle
What you need to do is check to see if the Page_Load is being triggered by a Postback.
private void Page_Load(object sender, System.EventArgs e)
{
if(!Page.IsPostBack)
{
///do stuff in here that you want to occur only on the first lad.
}
else
}
// code that you want to execute only if this IS a postback here.
{
}
// do stuff you want to do on Page_Load regardless of postback here.
}
You can use the IsPostBack property of the Page as follows:
protected override void OnLoad(EventArgs e) {
if (!Page.IsPostBack) {
EmptyTextBoxes();
}
}
Have you tried wrapping the form reset code in a check to see if the page is a postback?
if(!Page.IsPostback) {
// Do form reset here
}
You thought about using the IsPostBack page variable?
protected override void OnLoad(EventArgs e)
{
if(!IsPostBack){
//all your logic here.
}
}
if it's the case, you might use a databound control and set it to insert mode