IsPostBack sometimes doesn't work in asp.net webforms [duplicate] - javascript

The best explanation I've found for a postBack is from Wiki.
a postback is an HTTP POST to the same page that the form is on.
While the article does explain how a second page was needed in ASP, but no longer needed in ASP.NET, it doesn't give much detail or background. I am looking for a freakin' tome of information on PostBacks. Much like the simple question of "how can I clean a house" can be addressed by this 900 page book. I don't need 900 pages worth, but details please. I found a nice little tutorial for ASP.NET life cycle, but it seriously glosses over postbacks (amongst other things).
I am looking to the developers who have been around before .NET and really don't take these kinds of things for granted. Books and hyperlinks are reasonable answers or additions to your answer.

So far I've seen the right answer alluded to repeatedly, and almost everyone has come shy of what I consider subjectively to be the mark.
Let's start with the basics:
An HTTP request can be any of the HTTP verbs, but the two that people use most are GET and POST. Well, those are the two a programmer uses most frequently. The others all have some purpose, if they're implemented on the server. When you send information to the server, you can do so either through the use of the URL (to request a page) or within the body of the request (POST, PUT, DELETE, for instance).
Now you'll remark (I'm sure) that the URL in a GET request often contains data, and this is true, but according to W3C, you should not use GET to alter state, and yet we do often. It's sort of a hack that we all agree is an actual use, and not a hack. Whether that makes it a hack or an actual implementation detail I leave up to you.
So when you send the body of the POST (skipping the others for now, you can figure it out from here) with the form elements, you're sending back certain elements. How those elements are defined is up to you and to the environment you're working in. You could post to a server with a JSON element in the body, or with XML, or with form fields. Generally we do posts from a FORM element in the body of the HTML.
Now everyone says, "oh, a postback is a subsequent request to a page." But, that's not true. A postback is when you send data via POST -> back to the server. I say this because the difference between a GET request and a POST request is if data is included in the body (and the verb used, but the client usually knows how to deal with that). You could postback to the page on the first time the page is visited, and in fact ASP.NET has tools for doing that in the library. You could certainly have a desktop client POST data to a server (think Twitter) without showing any webpage at all from the server (ok, so twitter is probably not the best concept to use for an example here, but I want to illustrate that you can use a client that doesn't show the webpage, so no request is necessary).
So really what you should read there in "postback" is "I'm POSTing data BACK to the server for processing". It's presumed that you retrieved the page initially with a GET to show the user the <form> element that has <input> fields for them to interact with, and that at the end you're sending data back. But I hope you can see that it doesn't have to be in that order.
So here's something else to consider:
What if you gave the user a page with a bunch of <input>s and no <form> but instead, had a button wired up in javascript to concat all those <input>s with &value-n= and send them as a GET? Does the same thing, but violates that concept of only using GET for requests. (possibly) ensuing discussion encourages me to reinforce that GET should have no side effects (no updating values)
It's how come you can send someone a link to a google search, for instance. So we don't ALWAYS have to POST BACK to the server to get data.
Hope this helps.
Cheers

See ASP.NET Page Life Cycle Overview on MSDN for a good general introduction about what happens when a requests hits the server.
A PostBack is any request for a page that is not the first request. A PostBack will always be in response to a user action (triggered most commonly by a Button, AutoPostBack control or Ajax).

POSTBACK: Part of ASP.NET's contrived technique for hiding the true stateless nature of the web/HTTP behind a stateful facade. This results in complex code (IsPostback, ...), a hard to understand page lifecycle, many different events, ... and numerous problems (ViewState size, web-farm stickyness, state servers, browser warnings (not using PRG pattern), ...)
See ASP.NET MVC instead.

A post back is round trip from the client (Browser) to the server and then back to the client.
This enables you page to go through the asp engine on the server and any dynamic content to be updated.
here is a nice explanation

ASP.Net uses a new concept (well, new compared to asp... it's antiquated now) of ViewState to maintain the state of your asp.net controls. What does this mean? In a nutshell, if you type something into a textbox or select a dropdown from a dropdownlist, it will remember the values when you click on a button. Old asp would force you to write code to remember these values.
This is useful when if a user encounters an error. Instead of the programmer having to deal with remembering to re-populate each web control, the asp.net viewstate does this for you automatically. It's also useful because now the code behind can access the values of these controls on your asp.net web form with intellisense.
As for posting to the same page, yes, a "submit" button will post to an event handler on the code behind of the page. It's up to the event handler in the code behind to redirect to a different page if needs be (or serve up an error message to your page or whatever else you might need to do).

The Wikipedia definition of postback is pretty good, but I'd add the following:
A postback is a subsequent HTTP POST to the same page that the form is on.
If I have a page with a form on it and, rather than having my Submit button redirect the browser to another page that will process the form, instead have the Submit button refresh the current page (and perform some specific steps to validate/save the page, presumably), then that Submit button is said to have posted back to the current page.
Postbacks can be either full (refresh the entire page) or partial (in a case where AJAX is employed). A partial page postback will re-render only a part of the page (like a single drop-down list, a table, etc.).

In the old HTML, the only way to make something updated on the webpage is to resend a new webpage to the client browser. That's what ASP used to do, you have to do this thing call a "PostBack" to send an updated page to the client.
In ASP .NET, you don't have to resend the entire webpage. You can now use AJAX, or other ASP.NET controls such that you don't have to resend the entire webpage.
If you visit some old website, you would notice that once you click something, the entire page has to be refresh, this is the old ASP. In most of the modern website, you will notice your browser doesn't have to refresh the entire page, it only updates the part of the content that needs to be updated. For example, in Stackoverflow, you see the page update only the content, not the entire webpage.

Simply put this by a little code. Hope it is helpful to you.
When you firstly request the page url. you can view the source code of it in most browser. Below is a sample of it .
The essential of Post Back is actually call the __doPostBack which submit all the form data got from your firstly requested back to the server. (__EVENTTARGET contains the id of the control.)
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>
NHibernate Demo
</title>
<script language="javascript" type="text/javascript">
function dopost() {
__doPostBack('LinkButton1', '');
}
</script>
</head>
<body>
<h1>NHibernate Demo</h1>
<form name="ctl01" method="post" action="Default.aspx" id="ctl01">
<div>
<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
<input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKLTMxNzcwNTYyMWRkKHoXAC3dty39nROvcj1ZHqZ5FYY=" />
</div>
<script type="text/javascript">
//<![CDATA[
var theForm = document.forms['ctl01'];
if (!theForm) {
theForm = document.ctl01;
}
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}
//]]>
</script>
<div>
<input type="hidden" name="__VIEWSTATEGENERATOR" id="__VIEWSTATEGENERATOR" value="B2D7F301" />
<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEWAwKZx5vTCgKM54rGBgLM9PumD20dn9KQguomfpAOdTG0r9Psa7al" />
</div>
<a id="LinkButton1" href="javascript:__doPostBack('LinkButton1','')">LinkButton</a>
<input type="button" value="testPostBack" id="testpostback" onclick="dopost();" />
</form>
</body>
</html>

Postback is a request during which ASP restores values of controls' properties from view state.

Related

html script history.back() causes "Confirm Form Resubmission". How to suppress that browser prompt using my custom script? [duplicate]

I am in bit of a delicate situation here. In my organization we design stock management systems and it is a web application based on JSP pages and servlets which handles them.
I have been asked to fix a specific problem. We have a JSP page with an HTML form table where there are stock details. When user enters the details manually and submit the form, stock details updated in the database and it works fine.
Problem is this : When the user press the browser's back button, user can come to the previous page where he submitted the details. And when the user submit this, data is saved once more to the database.I need to prevent this behaviour.(Something likeclear and reload the page.)
Things I did so far : clear the browser cache.Code works fine but not the expected result.
Unfortunately I cannot share the code due to company regulations. What I need is a help to prevent this behaviour or a workaround.
Thanks in advance..
You can use a javascript function with the help of a hidden attribute to reload the web page. When the user press the back button,based on the value of the hidden attribute, page will be reloaded without loading the cached page.
Your approach of clearing cache is correct. Coupled with that, you can use this approach.
<input type="hidden" id="refreshed" value="no">
<script type="text/javascript">
onload=function(){
var e=document.getElementById("refreshed");
if(e.value=="no")e.value="yes";
else{e.value="no";location.reload();}
}
</script>
One drawback of this approach is if your clients' browsers have disabled JS, this will not work.Otherwise it should work.
When the user press the browser's back button, user can come to the
previous page where he submitted the details. And when the user submit
this, data is saved once more to the database.
According to how you described it, that is based on a doGet request. Which means every time you visit that URL, it will send the request with whatever parameters were added.
As someone already mentioned, if you switch the form to a post method and switch the Servlet to a doPost, you won't have this issue anymore.
Alternatively you can circumvent this with a javascript solution. Here are some options:
You can check if the user clicked the back button, disable form if true.
Another way is by storing a cookie which you check on page load, if it exists you can disable the form.
You can use this code also
$(document).ready(function() {
function disableBack() { window.history.forward() }
window.onload = disableBack();
window.onpageshow = function(evt) { if (evt.persisted) disableBack() }
});
You must use a Post-Redirect-Get pattern: https://en.m.wikipedia.org/wiki/Post/Redirect/Get.
Actually, every use of standard HTML forms with method="post" should be implemented with that pattern. It doesn't have any use for AJAX-posted forms, which actually could be another solution but will require more work and probably some architectural changes.
I had this same problem while building a django web app, and my solution was to not allow caching of the html that contains the form. In your request handler, do not allow the browser to cache the page. This will force the browser to get the page fresh from the document.
Which, in this case, you can just verify in your request handler if the requested form has already been submitted.
My code for reference:
from django.views.decorators.cache import never_cache
#never_cache
def GetForm(request, pk):
# Logic #
if (IsFormCompleted(pk)):
# Handle request #
Here is a solution.
give a random id in a hidden field on the form. Then on the server side, if the user resubmit, check if the random id already on the database. If so, redirect user.

Can I use post to click a button on a page in JQuery?

I'm trying to request a page and click a button on it without opening a window so I'm thinking post could work. Here is my code:
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"</script>
<script>
$(document).ready(function() {
$.post(
"http://m.roblox.com/Catalog/VerifyPurchase?assetid=161075864&type=tickets&expectedPrice=1",
$("ui-block-a").submit();
);
alert("work");
});
</script>
</head>
<body>
</body>
</html>
If I'm understanding post correctly, the first argument is the url to which it requests from and the second argument is the one where you can send data. I'm trying to send a request to click the "buy" button on the page if you follow the link. Can anyone help?
A post request sends data to a given URL. What the server does with that data from that point is entirely up to the server. It is very unlikely that the web page you are trying to simulate a button press on allows that behavior. If that was possible in general, it would leave users open to some very large security vulnerabilities. For example, a site could simulate donating money via PayPal without the user ever knowing.
In this particular case, the button appears to submit a form. In that case, you could always attempt to send the request directly to the page that the form submits to, which would simulate submitting the form. However form submissions are generally protected against stuff like this, because again, it could be used to act on behalf of the user.
Basically, the best option for something like this is to provide the user with instructions detailing what they need to do, and then open the page for them.
Assuming there is no other issues like CORS you can do the post like you are trying to do, but the following is invalid.
$.post( "http://m.roblox.com/Catalog/VerifyPurchase?assetid=161075864&type=tickets&expectedPrice=1", $("ui-block-a").submit();
You are doing a POST which required the data being send to the server to be in the request body and not the URL string.
When you post to a page you are actually posting directly to the server and not a page and in this case unless the $("ui-block-a").submit(); is returning data for the page you are posting to, it is not needed.
The following would be closer to what you are looking for with that post
$.post( "http://m.roblox.com/Catalog/VerifyPurchase", { assetid: "161075864", type: "2pticketsm", expectedPrice: "1" } );
If it was successful you should see a allow-orgins error in your developer / inspector console.
$.post() is an abbreviated form of $.ajax(), with POST pre-selected as type. There are also $.get() (with GET pre-selected as type), and $.load() (with the returned data immediately injected into the specified element). But $.ajax() is the grand-daddy of them all.
AJAX is a method of exchanging data with a processor file on a server, without leaving / refreshing the page you are on. That is, with AJAX (or $.post), you can send information to a processing page on the server -- such as: my_processor.php -- the processing page can do something with the data (for example, use the data to query a database), and then echo out data, which is returned to the originating page. The received data can then be injected into a DIV on the original page, or something of the sort.
An ajax routine is usually triggered by some event on the originating page (the user presses a button, or selects a value in a drop-down, or some such). Javascript (or jQuery) code detects the event, and the AJAX code is usually actioned in the javascript event.
Here are some simple examples of what has been described.

Display form result in same page with only client-side script possible?

I have a bit of a tricky work problem I hope to get some help with.
To handle various forms and storing entries, we use an in-house tool which I cannot modify. Basically what happens is:
I enter he URL the original page, and the URL of the destination page after successful submission.
The tool spits out some HTML and Javascript code, the most important of which is a unique URL, let's call it (redactedURL), that goes after the action attribute.
When the form is submitted, the page will refresh to one of two possible destination URLs: the one I inputted if success, or (redactedURL) if error.
I can download all the entries from the tool afterward.
The HTML is quite simple. checkform() is a simple validation script.
<form action="(redactedURL)" name="enenForm" method="POST" onSubmit="return checkForm()">
The issue with this is that I can't style the (redactedURL) error page, which is quite ugly. I am wondering if there is anyway I could
Suspend automatic display results of form submission
Determine the destination URL, and based on that, write out a custom thank you/error message (since I cannot access the server-side script, this seems to be the only solution to determine if the submission is successful or not).
Make sure that tool still properly stores all the entries.
Any help would be much appreciated. Thanks!
Don't use a form. Instead use AJAX. I think this SO Question will provide a start. Basically you use JavaScript to submit data to a server using XMLHttpRequest. The returned HTML is a string which you could either modify or (better yet) normalize and add to the DOM.
For an advanced example jQuery-Mobile does this concept when you click a link instead it gets the HTML from the server as an AJAX request copies the HTML inside the <body> and inserts it into the DOM.
Search for tutorials about AJAX and jQuery (or your prefered JS library). Like this one.

Refreshing page without losing checkboxes information in cakephp

I'm developing a website with CakePhp.
I have a view to select some items on a list, via checkboxes in a form, and each item has a "more info" link which refreshes the page with additional information of this item.
The problem is that if I click any "more info" link, I obviously lose the data about what checkboxes were selected before. The only thing I come up with is updating $this->Session each time a checkbox is changed, but I need to trigger a function in a controller when this happens.
Is there any other solution?
I've been searching everywhere and I've found some things about Javascript and JQuery, but I have no idea of how to do it this way neither.
Thanks in advance.
If you don't mind sending all the text it's quite easy:
<div class='article'>
<div>short textmore info</div>
<div class="more hidden">long text</div>
</div>
jquery part
$(".article").on('click', '.morebtn', function(){
$(this).parents('.article').find('.more').removeClass('hidden');
});
css
.hidden { display: none }
Here is a fiddle
The better solution is to use ajax request. Also not that hard to implement.
Here is a fiddle showing the very basic request. You could use the full $ajax request too if you want need to do more advanced requests.
note that the example of the ajax request does not work due to invalid url. The url need to be from the same origin as the current page (same protocol, domain and port) to make it work. There are work arounds but that's a different issue
Read up on AJAX, it's a really cool technology which will make it very simple to do what you need. Outline:
When the button is clicked, the browser sends an AJAX request to the server for the text to display somewhere on the page.
When the response (some HTML fragment from the server) is received by the browser, a function is called which looks like so:
function(data) {
$('#description').html(data);
}
Doing AJAX requests is 5-10 lines of code (mostly configuration + building the URL).
The main work is on server side where you need to write a controller which provides the texts.
Since the page is never reloaded, there is no need to preserve the form values.
To learn AJAX, start with this tutorial.

MVC3, switching between Views in the same page

I am working on a MVC project that is supposed to have one page only, with two zones. On one zone I have a Google Map with markers, and the second zone is populated with the selected marker's details.
The details view has a button that when clicked should change the entire view into edit mode without refreshing the page or redirecting it. I have used two views, for details and edit and with the help of ajaxForm function I am switching back and forth between these two views. I'm adding the ajaxForm on documentready for edit view.
<script type="text/javascript">
// wait for the DOM to be loaded
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$('#currentDiv').ajaxForm(function(data) {
$('#currentDiv').html(data);
});
});
</script>
The problem appears when on server-side an error appears while trying to save data from edit view and I want to return to the same edit view with the errors displayed. The ajaxForm handler is not added any more and even if the new values that will try to be saved are ok, the detail view is loaded in another page.
Unfortunately, the use of ajaxForm creates some other problems because I don't have control over the cases when the ajax call fails.
Any ideas on how could I fix this? Is it some other solution to switch between those two views without using ajaxForm and without refreshing the page?
I think there are a couple of different questions that you are asking.
First off, you add jquery handlers to deal with the case when you get a 500 type error from the server.
Something like the following. I suggest taking a look at the docs for more info.
$(document).ajaxError(function(event,jqXHR,ajaxSettings,thrownError){
if (jqXHR.status != 0){
window.location = <error page>
}
}
The second problem seems to stem around error handling of known errors (say invalid input). In this case I suggest the following workflow.
1) User clicks on edit button, taken to edit screen
2) User enters in data, use client side validation to do initial check
3) User submits, user is then taken to the view screen and is shown a
success or error message.
The server response could look like:
public ActionResult Edit(EditModel model){
if (!ModelState.IsValid)
{
return Json(new {successful = false, message = "Failed.."});
}
...
}
On the client side, your form callback should now handle the message and the fact it was successful or not. In my implementation, I used knockoutjs to create a "message" area that I could update and clear. (I created templates, etc).
Remember to use client side validation for the easy field validation stuff.... This will save a trip back to the server.
Yours could be quite simple, by popping up the message returned from the server.
Lastly, document ready only fires when the original document is done loading, never again for an ajax call (at least that is my understanding). Just put that code that is the document.ready at the bottom of the edit page. It will fire after the html it is targeting has already been rendered.
Hope that helps!
I have begun to move away from the asp.net views available in ASP.Net MVC due to some incompatibilities and/or unnecessary complexities when trying to achieve functionalities expected of AJAX enabled sites of the day.
I would recommend moving towards a design where you use "dumb" HTML files, use jQuery to download them using AJAX and drop them into a container (personally I use a div) and then use another AJAX call to gather the data from a controller. There are a number of advantages to this approach:
It establishes a real (not fake) separation between client side and server side code.
Html files can be cached on the client cutting down on the amount of data transmitted.
Binding of the Html elements becomes a client side task achieved using jQuery offloading processing cycles from the server.
Controllers essentially become collections of web methods which means they can be untilized by iPhone and Android apps making mobile deployment easier.
I realize this probably isn't the exact answer you're looking for and this may not be an option for you but my hope is that it will help someone at some point make a decision to move away from mixing HTML and server side code.

Categories