How can I avoid a postback message? - asp.net

I am relatively new in programming and I have a doubt about postback. I searched in some pages, but I couldn't solve my question.
I created a web page and I use postback in it that updates some informations in the page. That works without any problems. However, after the postback is fired, if the user presses F5, a message appears asking to confirm the form re-submit.
Why exactly this message appears and how can I avoid it?
If the user would press F5, I want the page reload, without any alerts.
I'm sorry if my question wasn't clear enough, but I really don't understand postback how much I'd like.. =)

By Default ,
The method is post means it will confirm while reloading the page.
The method is get means it wont ask anything.
Why this happens,Whenever the post method called severe action gonna happen in server,so it just confirms from the user.There is no need in the case of get Method.
I hope u are clear with this solution.

One way to avoid your issue is to place a hidden field on the page. When the form is submitted, check the hidden field. If no value, process the form, and populate the hidden field with a value. If it has a value, then do nothing.
I prefer using an on-click event on a button, instead of using the postback event.
As to why it happens, a refresh sends a request along with the form data back to the server causing another postback.

This is known as page re-submission.
When you refresh the browser, it will resend the last request you did. If it was a POST request (like you do in case of postback) then it will re-post the information but before doing it you'll see the warning message you describe.
To prevent this:
Page.Response.Redirect(Page.Request.Url.ToString(), true);
Which changes the response to a GET instead of a POST. Prevents the 'Form Resubmission' dialog.

I thought in the following code to solve my problem, using a javascript event:
$(document).keydown(function (event) {
if (event.keyCode == 116) {
location.href = 'pedidos.aspx';
return false;
}
});
It solves my problem, because I avoid the postback message as I want and the page is reloaded.
But is this a good solution?

Related

Reset input fields after submission

I'm working on an asp.net core project. I have some issues with the reset button. when I enter data which is already saved. The error message is shown as I given. After this reset button is not working.
I suggest after the submit, to either reset them with javascript, either if you use a post back, redirect to the same page (without post back this time).
For example this core redirects to him self, and the form is clear now.
Response.Redirect(HttpContext.Current.Request.RawUrl);
Or you can use this javascript code together and avoid the post back
OnClientClick="return (confirm('Clear Form ?') && this.form.reset(),false)"
Your question is very unclear, but it sounds like what you're talking about is actually the client-side validation. Once validation has been activated (by entering something into a field), validation will remain active. If you then clear that field (using the reset button, for example) and it's required, you'll still have a message saying the field is required, because it is, and it's now empty. If you want to clear all these validation messages, as well, then you need to do something like:
$('[type=reset]').on('click', function () {
let validator = $(this).closest('form').validate();
validator.resetForm();
});

ASP.Net save after hyperlink is clicked

I have a requirement to call a save method, that persists a model/object in the session, when the user leaves the page.
The page has various links that do not raise a postback but just perform a redirect. Are there any ASP.Net page life cycle methods I can hook into to perform the save without requiring a postback?
One solution could be to perform an asynchronous POST request (without waiting for a response) when the window is being unloaded:
An example using jQuery:
$(window).unload(function() {
$.post(location.href, $(document.forms[0]).serialize());
});
Although you will probably need to use a slightly different method for Chrome (found on jQuery forums):
It looks like the only way to get the
Ajax request to go through in Chrome
is to use the non-standard event
onbeforeunload. Chrome evidently
doesn't wait long enough to send the
Ajax request using onunload. It does
however wait for alerts...
Well that depends.
If you need to save values when the person leaves the page, then thats kinda hard.
What you can do, is to wrap all your links in some jquery, that says like:
Issue a Ajax Call, to AjaxSave.aspx, then it is completed, then window.location to the links href attribute.
BUT, that will only work if the person clicks on your links, not if the person just closes the browser or something.
You can also take the route to just save the stuff offen, so every time the person issues a post back, you just put the stuff in session. But that will mean that values changed from the last postback to the navigating away from the page is lost - don't know if that is an issue.
The last thing is to do like StackOverflow is doing. If you are editing stuff, it will show a warning when you leave the page, and then you have to click okay, to navigate away from the site.

Update Message on ASP.NET ModalPopupExtender

I have a form in a MS AJAX ModalPopup Extender, which is in a UpdatePanel (for async loading). Everything works as expected. There is one thing that I am trying to do but not sure how to do it.
On form submission, there is server side validation on top of client side validation. My question is: what is the best way to display validation error messages if any? It would be ideal if the messages could be written to the popup asynchronously so that the popup is still there.
If this is not possible, I am thinking of displaying the messages using the JavaScript alert box.
Any insight and suggestions are greatly appreciated.
John
It's been awhile since I have used the ModalExtender and UpdatePanels but this is possible. Essentially (rust falling out of head), I had a label inside of the modal set to visible=false. Then, on clicking the Ok button, I called a function in the code behind that processed the logic. If the logic failed, then I updated the label text and set visible = true. If the logic passed, I called the close() property of the modal. With both, you have to call updatePanel.update() so that the content is refreshed. Let me see if I can find an example...
Not Exactly what I was looking for, but it may help you get on the right track:
If (logInstance.isNew) Then
result = logInstance.createNewLogEntry()
If (result.ToLower = "success") Then
Response.Redirect("default.aspx?status=1")
Else
saveErrorType.InnerHtml = result
ModalSaveError.Show()
End If
Else
result = logInstance.updatePreviousLogEntry(textReasons.Value)
If (result.ToLower = "success") Then
Response.Redirect("default.aspx?status=2")
Else
saveErrorType.InnerHtml = result
ModalSaveError.Show()
End If
End If
Tommy, thanks for the reply. Instead of replying to you as a comment, I am doing it as an answer, hoping that somebody can tell me if this is the best we can do.
Also it may be of some help to those who face the same situation.
After posting yesterday I spent a couple more hours on it and found a solution, which is basically the same idea as you described in your answer.
The key issue was that I am not using the OK button of the extender. Instead I used a regular linkbutton which triggers a server side click event when clicked. This event closes the popup regardless of the validation result. So my goals was to keep the popup open or at least make it appear to be open and then add whatever validation error message to it.
After I cleared my thought on the issue, I figured I should be able to re-open the popup and populate the form with the data that the user is working on, and adding my validation error messages to it.
That did it!
Thanks again.

What can prevent a Postback in ASP.NET?

We have a user who is having problems with a ASP.NET app. The user hasn't been available to gather many details, but at this point our best guess is that the PostBack is not occurring. Something is going wrong between when the user clicks the LinkButton and when the HTTP Request is supposed to be made.
(User does have JS enabled)
Beyond solving the immediate problem, it might be helpful for posterity to assemble the canonical list of things that can break PostBack behavior of ASP.NET controls.
If you have say a button that has a postback event as well as a javascript event on click, if the javascript event that is fired returns false postback will be stopped.
I would first check that your <form> tags are well formed and that you don't have nested <form> tags. Both times I've debugged something to do with postback this turned out to be the problem. It's confusing because it's a browser dependent issue.
Having a self-closing <script /> tag can stop postbacks occurring. Get the user to send you any javascript errors from their log. There is actually a decent JS debugger in IE8 (about the only good thing in it!).
a form with no method attribute, or method note being set to POST
an onsubmit event handler that does not return true
trying to submit the form programatically, but unable to locate the form by id as there is another element with the same id on the page

How do I remove a page from the browser history?

I have an have an ASP.Net page which contains a button. This Page contains a ServerSide Paypal button.
When pushed my server does various clever things on the back end and then rewrites the response as a form and some javascript which posts this form to paypal..
This all works great.
However, if the user then elects to click back, they will arrive at my generated self-posting form and that will forward them again to Paypal.
I thought if I could find a way to have my generated form page not exist in the history, then this will solve my problem. but I have no idea how to correct this.
How can I remove my page from the history or just have it never appear?
Update: Thanks to all... Those are some great answers. Upvoted all good ones but went with splattne on account of clever use of hidden field rather than cookies for basis of decision.
window.location.replace(URL);
window.location:
replace(url)
Replace the current document with the
one at the provided URL. The
difference from the assign() method is
that after using replace() the current
page will not be saved in session
history, meaning the user won't be
able to use the Back button to
navigate to it.
I'm not sure if that can be done. But here is an idea how you could prevent that resubmit of the form.
You could insert a hidden input in your form which at the beginning would be empty. On submit you'll write a value in that field and make sure you check on every submit attempt if this field is empty.
If it is not empty on submit you know that the form was previously sent and you could warn the user.
As a web application, you'll never have full control of the user's browser. Even if there was a way to instruct the browser to not store the page in history, which I doubt, you can't be sure it'll work. For example, a clever user could tweak an open-source browser to store every page in history, no matter what.
I think you should try to approach the problem from another angle. You could, for example, detect that it's the same form which is being forwarded and not send it to paypal the second time. The important thing is to do it server-side.
Perhaps you could set a cookie before submitting the form.
When the page is loaded, check for the existence of that cookie (meaning the form was already submitted). If found, instead of automatically submitting the form, automatically go back (window.history.back()) again.
I'm not sure if you can do this easily with PayPal integration, but the
"Post / Redirect / Get" pattern can be used to address this problem
A useful Hint for some might be this...
window.history.go(-2);
particularly in the advent of a load failure warning popup.
You could simply programme your page not to submit, or to do something / navigate somewhere else, if window.referer is the Paypal page you are trying to avoid invoking a second time.
protected void Page_Load(object sender, EventArgs e)
{
Page.RegisterClientScriptBlock("", "<script>if(history.length>0)history.go(+1);</script>");
}

Resources