What methods are available to stop multiple postbacks of a form in ASP.NET MVC? - asp.net-mvc

A common web problem is where a user clicks the submit button of a form multiple times so the server processes the form more than once. This can also happen when a user hits the back button having submitted a form and so it gets processed again.
What is the best way of stopping this from happening in ASP.NET MVC?
Possibilities as I see it are:
Disable the button after submit - this gets round the multiple clicks but not the navigation
Have the receiving action redirect immediately - browsers seem to leave these redirects out of the history
Place a unique token in the session and on the form - if they match process the form - if not clear the form for a fresh submit
Are there more?
Are there some specific implementations of any of these?
I can see the third option being implemented as an ActionFilter with a HtmlHelper extension in a similar manner to the anti-forgery stuff.
Looking forward to hearing from you MVC'ers out there.

Often people overlook the most conventional way to handle this which is to use nonce keys.
You can use PRG as others have mentioned but the downside with PRG is that it doesn't solve the double-click problem, it requires an extra trip to the server for the redirect, and since the last step is a GET request you don't have direct access to the data that was just posted (though it could be passed as a query param or maintained on the server side).
I like the Javascript solution because it works most of the time.
Nonce keys however, work all the time. The nonce key is a random unique GUID generated by the server (also saved in the database) and embedded in the form. When the user POSTs the form, the nonce key also gets posted. As soon as a POST comes in to the server, the server verifies the nonce key exists in its database. If it does, the server deletes the key from the database and processes the form. Consequently if the user POSTs twice, the second POST won't be processed because the nonce key was deleted after processing the first POST.
The nonce key has an added advantage in that it brings additional security by preventing replay attacks (a man in the middle sniffs your HTTP request and then replays it to the server which treats it as a legitimate).

You should always return a redirect as the HTTP response to a POST. This will prevent the POST from occuring again when the user navigates back and forth with the Forward/Back buttons in the browser.
If you are worried about users double-clicking your submit buttons, just have a small script disable them immediately on submit.

You might want to look at the Post-Redirect-Get (PRG) pattern:

This really isn't MVC specific, but the pattern we follow on our web pages is that actions are performed with AJAX calls, rather than full page POSTs. So navigating to a url never performs an action, just displays the form. The AJAX call won't be in the history

Along with the disabling of buttons, you can add a transparent div over the entire web page so that clicking does nothing. We do this at my work and add a little friendly label saying processing request..

The most elegant solution I found was to use ActionFilters:
Blog post is here

Related

Best practice/design for a multi-page form in .NET MVC3

I am working on a web application that involves the user filling out a multi-step form that spans several pages. The form has tabbed navigation across the top (these links do not submit the current page) and a next button at the bottom (which does submit). I am considering several strategies for handling form submission/validation:
one action method and view per form page. When you hit next, it submits the form to the action method for the next page. If there are validation errors, you are redirected back to the previous page:
URL's are descriptive and can be copy-pasted
Only redirects in the error case
Since the redirect does not have the form data, we lose context about the submission which makes it hard to display certain error messages
The same validation logic works for redirecting the user if they try to visit a step in the flow that they aren't ready for yet
one action method and view per form page. When you hit next, it submits the form to the current page action. If there are validation errors, the same view is returned. Otherwise, we redirect to the next page action:
URL's are descriptive and can be copy-pasted
Redirects are very common (not sure if this is bad)
When displaying validation errors, we are in the same request as the form submission so we have full access to the invalid input
Have to pass additional context if we want the ability to, for example, add a "Previous" button which also submits
one action method for ALL pages. URL's contain additional context about the step being submitted (e.g. MyController/MyAction/{step}). The controller message selects which view page to return depending on validation and the current step.
URL's are not descriptive (e. g. if I submit step 1 to go to step 2, then the URL the user sees will be the same regardless of whether page 1 (invalid) or page 2 is returned
No redirects
When displaying validation errors, we are in the same request as the form submission so we have full access to the invalid input
A different method I haven't listed here
I have tried to enumerate what I see as some of the pros and cons of each method, but I would be interested to know:
What are other pros and cons of these methods? Are mine correct? Could some of the cons I've listed be designed around?
Is there a standard approach to this problem which I should be using? If so, why is it the standard approach?
I would highly recommend option 2 with a minor modification. You may want to think about also creating one view model per action/view as well. If you have one model that spans all the pages, validation will occur across ALL properties, meaning that even though the user can only edit part of the model on each screen, they could get validation warnings for properties they can't see. We did this recently in a project and it worked beautifully. You have to do some data manipulation in the back-end to combine everything back together, but it was worth it in the end.
As you said, your URLs would be deep-linkable, which means users can Copy/Paste, and more importantly, they can add the page as a favorite in their browser, allowing them to come back to the same place very easily. In my opinion this makes option 3 obsolete.
You will also benefit from the fact that all of your logic for navigation is occurring in one place. You'll have to store the state of the "wizard" on the client (which page you're currently on) so that your controller knows what to do on submit. You'll want to analyze the state of the wizard and make a decision for where the user needs to go next. If you go with option 1, you won't know where you "came from" and server-validation errors will be difficult to display to the client. This is a beautiful example of the POST - REDIRECT - GET pattern. Each page would have 2 actions, a GET that takes simple ids, and a POST which takes more complex models. Post the server, figure out where to go next, redirect to a GET.
Lastly, consider your previous button simply linking directly to the previous step, instead of submitting the form. Otherwise, the user could potentially get stuck on an invalid step. This happened to us and again, worked very nicely.
Hopefully this was helpful. Good luck!

Reset Struts2 Token?

I have a token interceptor to block double submitting a form which works great, but I'm looking to reset the token under circumstances.
Essentially what I've got in the page is a list of criteria and a submit button. When the user clicks the submit button, the criteria is stored as a new row in a specific table in the database. An ajax call updates the div underneath the form with a succeeded or failed message. The token works in that I don't want the user attempting to add duplicate rows. However, if you user changes the criteria (either by choosing a different option in a drop-down menu or editing the text in s:textfield) I want it to reset the token to allow form submission again. Currently the user has to go back and fill out a new form which is somewhat inconvenient.
I'm using the standard s:token in the .jsp and interceptor lines in struts.xml. I've been searching for something to reset the token but I haven't found anything. Thanks.
The token is a value in session under "struts.token" and in the form as "struts.token.name".
Since you're making an Ajax request underneath the easiest would likely be to set the session token to whatever is already in the form, or to create your own token interceptor (it's quite short, although it uses a static TokenHelper class, which is unfortunate–noted and logged as something to do) that changes the definition of "multiple" submit. (Hash of form vals? Not sure, never given this much thought.)
I couldn't find any answers on google and I don't appear to be getting any answers here so what I did is created a new button called "Clear Form" which calls some javascript to refresh the page and therefore resetting the token and the forms. Not the most elegant but it works.

Ruby/RoR and many subprocesses

I am trying to build a free web application using ruby/rails It should be able to send sms through online forms of various mobile operators. (like this one (in russian)).
So, I need to
wait for the user, who wants to send an sms through my website.
establish connection to operator website. Probably, using Mechanize.
retrieve captcha
show captcha to the user
allow user to enter a message and captcha
submit form on operators website (with message, captcha, phone number)
The connection to the operator website should be alive during all this process (otherwise captcha will change). As far as I understand, I need to create a (sub)process each time sms is sent.
Could you please advise what is the best way of handling this in rails\ruby?
I am still rather new to web-development...
Should I use threads? forks? popen? using PTY? some external gem? How should I communicate with my process?
Assuming there's nothing special about the operator's web site, no, you don't need to keep a connection alive during the whole process. Generally speaking, forms on web pages work like this: You visit the URL, your web browser downloads the page with the form on it. In your case, it will also have an <img> tag or similar to show the CAPTCHA. Once your browser has downloaded the page, the connection is severed. After you fill out the form and click on Submit, your web browser opens a new connection to the server and sends the data, and the server sends its response (whatever page is shown after you click Submit).
All your program has to do is emulate this experience. So: 1) Download the page with the form on it. Scrape the form fields (make sure you don't miss any hidden fields--with a CAPTCHA there will probably be some) and the CAPTCHA. 2) Build a page to show your user that includes the CAPTCHA and a form with all the fields they need to fill out. If there were hidden fields in the original form, make sure you include their values (as hidden fields in your form) as well, because when the user submits your form you'll need them. 3) Then, when the user submits your form, send the data, including the hidden values and what the user entered for the CAPTCHA, to the operator. 4) Finally, check if the operator indicated success, and build a page to tell your user.
If you're doing this in Rails, you'll probably have two methods in your controller: One called e.g. 'show' (steps 1 and 2 above) that will scrape the CAPTCHA and other info from the operator's site and show the user your form view, and one called e.g. 'send' (step 3 and 4 above) that the form will submit to, and which will take their data and send it to the operator's web site, collect the response and tell your user if it was successful or not.
Note: You'll want to read the operators' terms of service before you bother with any of this. I'm fairly certain that this kind of thing will be against their TOSes and if they notice your server sending a lot of requests their way they're going to block you pretty quick.
To answer another question of yours, you can use DRb or background_job (aka BJ) to actually accomplish the sending in the background so that after your user submits the captcha they don't have to wait for the response. Or you could wrap this in ajax and have the DRb/BJ process notify you when the sms sending has happened so you can notify the user of success or any problems.
Typically opening threads in Ruby is something to avoid as there are so many great gems that do what we need. Not to say that you shouldn't use threads, just that for the most part it's probably already been done really well.

What is a postback?

I'm making my way into web development and have seen the word postback thrown around. Coming from a non-web based background, what does a new web developer have to know about postbacks? (i.e. what are they and when do they arise?)
Any more information you'd like to share to help a newbie in the web world be aware of postbacks would be most greatly appreciated.
The following is aimed at beginners to ASP.Net...
When does it happen?
A postback originates from the client browser. Usually one of the controls on the page will be manipulated by the user (a button clicked or dropdown changed, etc), and this control will initiate a postback. The state of this control, plus all other controls on the page,(known as the View State) is Posted Back to the web server.
What happens?
Most commonly the postback causes the web server to create an instance of the code behind class of the page that initiated the postback. This page object is then executed within the normal page lifecycle with a slight difference (see below). If you do not redirect the user specifically to another page somewhere during the page lifecycle, the final result of the postback will be the same page displayed to the user again, and then another postback could happen, and so on.
Why does it happen?
The web application is running on the web server. In order to process the user’s response, cause the application state to change, or move to a different page, you need to get some code to execute on the web server. The only way to achieve this is to collect up all the information that the user is currently working on and send it all back to the server.
Some things for a beginner to note are...
The state of the controls on the posting back page are available within the context. This will allow you to manipulate the page controls or redirect to another page based on the information there.
Controls on a web form have events, and therefore event handlers, just like any other controls. The initialisation part of the page lifecycle will execute before the event handler of the control that caused the post back. Therefore the code in the page’s Init and Load event handler will execute before the code in the event handler for the button that the user clicked.
The value of the “Page.IsPostBack” property will be set to “true” when the page is executing after a postback, and “false” otherwise.
Technologies like Ajax and MVC have changed the way postbacks work.
From wikipedia:
A Postback is an action taken by an
interactive webpage, when the entire
page and its contents are sent to the
server for processing some information
and then, the server posts the same
page back to the browser.
Expanding on the definitions given, the most important thing you need to know as a web-developer is that NO STATE IS SAVED between postbacks. There are ways to retain state, such as the Session or Viewstate collections in ASP.NET, but as a rule of thumb write your programs where you can recreate your state on every postback.
This is probably the biggest difference between desktop and web-based application programming, and took me months to learn to the point where I was instinctively writing this way.
Postback happens when a webpage posts its data back to the same script/dll/whatever that generated the page in the first place.
Example in C# (asp.net)
...
if (!IsPostback)
// generate form
else
process submitted data;
Web developement generally involves html pages that hold forms (<form> tags). Forms post to URLs. You can set a given form to post to any url you want to. A postback is when a form posts back to it's own page/url.
The term has special significance for ASP.Net WebForms developers, because it is the primary mechanism driving a lot of the behavior for a page — specifically 'event handling'. ASP.Net WebForms pages have exactly one server form which nearly always posts back to itself, and these postbacks trigger execution on the server of something called the Page Lifecycle.
The term is also used in web application development when interacting with 3rd party web-service APIs
Many APIs require both an interactive and non-interactive integration. Typically the interactive part is done using redirects (site 1 redirects a user to site 2, where they sign in, and are redirected back). The non-interactive part is done using a 'postback', or an HTTP POST from site 2's servers to site 1's servers.
When a script generates an html form and that form's action http POSTs back to the same form.
Postback is essentially when a form is submitted to the same page or script (.php .asp etc) as you are currently on to proccesses the data rather than sending you to a new page.
An example could be a page on a forum (viewpage.php), where you submit a comment and it is submitted to the same page (viewpage.php) and you would then see it with the new content added.
See: http://en.wikipedia.org/wiki/Postback
Postback refers to HTML forms. An HTML form has 2 methods: GET and POST. These methods determine how data is sent from the client via the form, to the server. A Postback is the action of POSTing back to the submitting page. In essence, it forms a complete circuit from the client, to the server, and back again.
A post back is anything that cause the page from the client's web browser to be pushed back to the server.
There's alot of info out there, search google for postbacks.
Most of the time, any ASP control will cause a post back (button/link click) but some don't unless you tell them to (checkbox/combobox)
Yet the question is answered accurately above, but just want to share my knowledge .
Postback is basically a property that we can use while doing some tasks that need us to manage the state of the page, that is either we have fired some event for e.g. a button click or if we have refreshed our page.
When our page loads for the very first time , that is if we have refreshed our page, at that time postback-property is false, and after that it becomes true.
if(!ispostback)
{
// do some task here
}
else
{
//do another task here
}
http://happycodng.blogspot.in/2013/09/concept-of-postback-in.html

Preventing double HTTP POST

I have made a little app for signing up for an event. User input their data and click "sign me in".
Now sometimes people are double in the database, the exact same data that got inserted 2 times very quickly after each other. This can only mean someone clicked the button twice, which caused two posts to happen.
This is common web problem, as credit card apps and forum apps often say: "Clicking once is enough!".
I guess you could solve it by checking for the exact same data to see if the post is unique, but I wonder if there are other methods.
This ofcourse does not count for ASP.NET webforms, because POST doesn't matter as much.
While JavaScript solutions can disable the submit button after it has been clicked, this will have no effect on those people who have JavaScript disabled. You should always make things work correctly without JavaScript before adding it in, otherwise there's no point as users will still be able to bypass the checks by just disabling JavaScript.
If the page where the form appears is dynamically generated, you can add a hidden field which contains some sort of sequence number, a hash, or anything unique. Then you have some server-side validation that will check if a request with that unique value has already come in. When the user submits the form, the unique value is checked against a list of "used" values. If it exists in the list, it's a dupe request and can be discarded. If it doesn't exist, then add it to the list and process as normal. As long as you make sure the value is unique, this guarantees the same form cannot be submitted twice.
Of course, if the page the form is on is not dynamically generated, then you'll need to do it the hard way on the server-side to check that the same information has not already been submitted.
Most of the answers so far have been client-side. On the server-side, you can generate a hidden field with a GUID when you first produce the form, and then record that GUID as a submitted form when the post is received. Check it before doing any more processing.
Whenever a page is requested from the server , generate a unique requestToken , save it in server side,mark status as NOT Processed and pass it along with the current requested page. Now whenever a page submit happens , get the requestToken from the "POST"ed data and check the status and save the data or take alternate action.
Most of the banking applications use this technique to prevent double "POST"ing.So this is a time proven & reliable way of preventing double submissions.
A user-side solution is to disable the submission button via Javascript after the first click.
It has drawbacks, but I see it often used on e-commerce websites.
But, it won't never replace a real server-side validation.
Client side techniques are useful, but you may want to couple it with some server side techniques.
One way to do this is to include a unique token in the form (e.g. a GUID or similar), so that when you come to process the form you can check to see whether the token has already been used, preventing a double submission.
In your case, if you have a table with event visitors, you might include this token as a column.
A client-only solution won't be enough, as stated in many of the answers here. You need to go with a server-side fail-safe.
An often overlooked reason that disabling the submit button doesn't work is, the user can simply refresh the submit target (and click OK on the "are you sure you want to resubmit the POST data?" dialog). Or even, some browsers may implicitly reload the submitted page when you try to save the page to disk (for example, you're trying to save a hard-copy of an order confirmation).
Almost no one has js disabled.
Think about coding your e-commerce website for the 70 year old woman who double clicks every link and button.
All you want to do is add a javascript to prevent her clicking "Order Now" twice.
Yes - check this at the server side too "be defensive" - but don't code for that case. But for the sake of a better UI do it on the client side too.
Here are some scripts that I found:
//
// prevent double-click on submit
//
jQuery('input[type=submit]').click(function(){
if(jQuery.data(this, 'clicked')){
return false;
}
else{
jQuery.data(this, 'clicked', true);
return true;
}
});
and
// Find ALL <form> tags on your page
$('form').submit(function(){
// On submit disable its submit button
$('input[type=submit]', this).attr('disabled', 'disabled');
});
None of the solutions address a load-balance server.
If you have some load balancer, send a UUID (or any type of unique number) to the server to store and read again will not work well if the server is not aware of other servers, because each request could be processed by a different server in a stateless environment. These servers need to read/write to the same place.
If you have multiple servers you will need to have some shared cache (like a Redis) among the servers to read/write the unique value in the same place (what could be an over-engineering solution, but works).
Client side alteration is a common technique:
Disable submit button
Change the screen to a "please wait" screen
If the form was modal, changing the screen back to their usual process (this has the benefit of making things look really slick)
But it's not perfect. It all relies on JS being available and if that's not the case, without back-end duplication detection, you'll get duplicates still.
So my advice is to develop some sort of detection behind the scenes and then improve your form to stop people with JS being able to double-submit.
You can track the number of times the form's been submitted and compare it to the number of unique visits to the page with the form on it in the session.
Beside the many good techniques already mentioned, another simple server-side method, that has the drawback of requiring a session, is to have a session variable that is switched off on the first submit.

Resources