Disable Button During Postback With Server-Side Validation - asp.net

Been through a few threads and wasn't able to find this situation exactly. My page is ASP.NET 4.5, C#. I use "Server Side" validation for (IMHO) security reasons and have several validation groups on a dynamic form.
I think we are all familiar with the advantages of disabling a button during Postback to prevent double clicking. I've read through quite a few threads with examples using OnClientClick in various ways.
What I'd like my page to do is something like this:
1 - User clicks Submit (or whatever button)
2 - Server-side custom validation fires on appropriate validation group
3 - if the validation passes, disable the client button(s) and proceed with Postback
4 - if the validation doesn't pass, show the error as usual. Client buttons should still be enabled.
Number 3 seems to be the kicker. Is this even possible with server-side validation? It seems out of order to validate server-side, come back to execute javascript, then back to postback. If it is possible, then I'm muddy on some of the mechanics. Specifically, how to tell the client that the specific validation group passed okay on the server side. Less specifically, the entire thing, lol.
Thanks!

Since you're using ASP.NET, I'm assuming you're also using jQuery (which is the default).
$('#MyForm').submit(function (event){
event.preventDefault();
var form = $(this);
if (!form.data('submit-lock')){// check if we're waiting on the server's response
form.data('submit-lock', true);// set the lock since we're about to post to the server
$.ajax(/*your url and data and whatnot here*/)
.always(function(){
form.data('submit-lock', false);// the server responded, unlock
});
}
});
$.ajax() returns a jQuery Deferred promise object.
promise.always(function) registers a function to call when the ajax is resolved (success) or rejected (fail).
More reading on the deferred pattern:
http://joseoncode.com/2011/09/26/a-walkthrough-jquery-deferred-and-promise/

Related

jQuery validation for ASP.NET, security issues

I would like to replace asp.net form validation with jQuery validation but not sure is this secure. ASP.NET validation use client side and server side validation to prevent hack post to server by disabling client side JS validation.
If I will use client side jQuery validation then it can be easily compromised, no? Maybe I am missing something?
You should not use ONLY client side validation. It can be easily avoided. People generally use client side validation for the User Experience. That way forms don't have to do a full post to catch mistakes. You want to do server side validation for security purposes.
jQuery validation is exactly the same as client side JS validation. jQuery is javascript framework.
ALWAYS use server side validation, and if you want to improve the user's experience then include your client side validation.
you should always write server-side validation code even if you validate the data on the client, otherwise your site will be unsafe and easily could be hacked. But the reason for writing client-side validation is to avoid the round-trip to the server that would otherwise be required to validate the data. In other words, if the user enters invalid data, it's much more efficient and user-friendly to trap the error before
sending the data to the server, where if the data is invalid you'll have to rebuild the page and maintain the page state as well so that the user can fix the invalid value.
Try using asp.net AJAX plus server control validators as your validation framework for the following reasons:
It's secure because your validation runs in the server side
It's easier to implement because you dont have to write the same code twice, both in the server and in the client (javascript)
Server side code it's by far much easier to maintain than client side code
Your website will look responsive, although you must take care on how to reduce the data traveling in every partial postback. Research on this.
You are tied to the asp.net sintax and your developers will love this too. You won't actually need more.
Recommendations:
focus is lost on every partial postback: the DOM portion of the form submitted inside the update panel is replaced, and the browser does nothing to set the focus for the user. So make sure to set the focus on the proper controls thinking the user is entering data using the TAB keystroke.
if you want to customize the appeareance of your server validator controls with css, try inheriting the main validators: Custom, Regex and requiredField, with your own classes, which basically set and unset the error css class and message you want every server roundtrip (set before rendering). then map those custom classes to the framework's classes in the web.config (use tagmapping), so you alway use the default markup for server side validations. You get this way the best of the two worlds.
Jquery.validate.js
https://github.com/jzaefferer/jquery-validation
You can set this up to run independently of your own client side validation/instead of/or in conjunction with.

How does RequiredFieldValidator automatically stops database being updated?

My previous impression of RequiredFieldValidator and similar have been that they show you an error label and set Page.IsValid false and that is it. Meaning they leave the rest of the task (preventing the use of wrong input data) to you. But today I have realised say if you use a DetailsView to insert a new record to a database, and you use validators to check the TextBoxes inside the DetailsView, they automatically prevent the database from being updated.
I would like to know how this is implemented behind the scene. I'm guessing it aborted the Page Lifecycle at Validator.PreRender event, so that database connections at later stage could not be reached? I'm probably wrong.
I'm trying to use Reflector to get inside the RequiredFieldValidator to see how it is implemented, but I don't really know where to look. Can someone give some hints?
This article explains the validation in detail for ASP.NET.
http://msdn.microsoft.com/en-us/library/aa479045.aspx
Validation can be both Server side and/or client side. If used, client side validation doesn't let user submit the form until it is validated. Client side validation is implemented using JavaScript and DOM. Every submit button is wired by the framework to check validation before doing post back.
Server side validation works differently. The event chain is extended between page load and event procedure call. The validation results are set, which can be interpreted by any event procedure.
In your situation I guess you have client validation on - which it prevents Form from being submitted to server and that's why no actual update to database is done.
EDIT: DetailsView control does support server side validation controls. Follow this link for details http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.detailsview.aspx#security

ASP.net viewstate changes validation and jQquery AJAX

Ok, so the problem is as follows: I'm using jQuery's AJAX in order to make behind the scene calls within the page (on events such as voting an item) and changing the content in the appropriate element. The problem occurs when I mix AJAX with ASP.net's AJAX, more precisely when I try to do a postback AFTER I've used jQuery on the page to perform an action. The page's viewstate is changed and validation fails (which would seem somewhat normal as a matter of fact).
My question is: can I disable the validation somehow so that I can perform postbacks combined with the chaged page viewstate? So far searching on how to disable it yielded no results.
A more practical example is on a comments page where I allow voting the comments and posting new comments as well. So should a user vote a comment and THEN post his own, the page's contents is changed, and thus validation fails. Also, I've tried placing the comment form within an update panel as to prevent the entire page from posting, but it still fails.
Of course I could use an alternate route and have a different page for handling the event and just call that via jQuery's AJAX, but I was wondering if I could do this by combining ASP.net and jQuery.
Thanks in advance.
If you want to disable viewstate verification, you can set it at the page or config level by using Page.EnableViewStateMac = false.
http://msdn.microsoft.com/en-us/library/system.web.ui.page.enableviewstatemac.aspx
It's not necessarily a good idea though because the validation functionality is there to protect from viewstate tampering, which you'll be turning off...
If you're running into issues with invalid viewstate because of jQuery ajax calls, one option is to consider using the Ajax controls, such as the UpdatePanel. You can wrap certain controls and mark the UpdatePanel as conditional to ensure a small round trip. This will not interfere with viewstate and allow you to continue to use viewstate validation and ajax at the same time.
There may be ways to use jQuery ajax calls and not interfere with viewstate validation. Others may be able to highlight this approach.

Is javascript reliable for preventing actions on the front end such as form submission?

I have a webservice that I need called, the result of which determines whether or not the user is allowed to submit the form.
Since this call is from javascript and not from code behind is it not reliable? Is there any way the user can get around the check -- by either going in with firebug and enabling the submit button, somehow making the method give a different result than was actually returned by the webservice, any other ways of being able to get around it?
Basically is there any way to call a webservice from javascript and have it's result determine whether or not a form can be submitted, and actually prevent the user from submitting the form at all? -- whether or not they have firebug, etc...
No, not possible.
Just to name a few possible reasons:
what if javascript is disabled?
what if the user submits the raw POST (using libcurl, for example)?
what if the browser, that the user is using interprets javascript in a way, different from your expectations (think, portable devices)?
Javascript validation is there for your users' convenience only and should never ever be used as a means of providing security.
You can never prevent the user from making an HTTP request that mimics submission of the form. While disabling the form via Javascript prevents submission for 95% of the users who both have Javascript enabled and don't want to circumvent your access control, anyone who understands HTTP can make the call and you are correct in showing that anyone with Firebug can do it in a matter of seconds.
Javascript isn't reliable for preventing anything. It shouldn't be seen as a security-wall, as it's too easily disassembled with things like firebug, iedevelopertoolbar, and many other browser toys.
Even if you could prevent them from submitting your form on your page, nothing stops them from creating a brand new form, on their own page, and point it toward the action of your form. Thus they're removing themselves from your "secure" environment, and instead chosing to play in their own.
Your suspicion is correct; the user can easily get around any possible Javascript validation.
You will need to use server-side code.
No, it is not reliable. Try disabling Javascript in your browser to see for yourself how easily you can get around it.
The user could simply disable javascript in their browser, or use something like NoScript. The best you could do is to try setting the form action itself in the return from the Ajax request, that way the form, as loaded, won't submit (except to itself). This will probably stop casual users but would be no impediment to a slightly more determined (or just bored and tech savvy) user. You will need to check on the server side whatever you do.
In general, no. You can make the form hard to submit without going through Javascript. Make the submit button not an actual submit button (<input type="submit">), but a pushbutton (<input type="button">) that submits the form in its onClick handler.
As everyone else said, no you can't do it. The only real solution is to have the web service return some dynamic value which the Javascript inserts in a hidden form input. Then whatever server-side code processes the form submission should reject the request if that value is not present.

Asp.net server control same event handling order on server-side/client-side

I have an asp.net server control (with the asp: in its definition). The button has been set to do post back.
On the server side, I have the on click event handler
e.g btnSave_click()
On the client side, I have a javascript function to be invoked on the click event
e.g btnSave.Attributes.Add("onclick","javascript: return CheckIsDirty();")
Am not sure which order these two will be executed. Because I want first on the client side to warn of any data entry fields that are not yet filled-out before actually saving any data.
Any help?
First client side, second server-side.
So you can use it.
I also use it in some cases, like:
close.Attributes["OnClick"] = "return confirm('Are you sure?')";
In this case if the user presses 'No' then the server-side event handler does not even play a role.
The trick here is to set this global variable "Page_IsValid" false if your test fails and this will stop the post back.
Read this page http://msdn.microsoft.com/en-us/library/aa479045.aspx which explains both server side and client Validation. There is sone good code example you can use.
The way you are setting your onClick JavaScript event will actually prevent it from posting back as you are overwritten the ASP.NET event handler. The correct way to accomplish the validation you are intending is to:
btnSave.Attributes.Add("onclick", "CheckIsDirty();" + GetPostBackEventReference(btnSave).ToString());
Notice that you append the result of GetPostBackEventReference, so that in JavaScript you first call your CheckIsDirty() method and then call the ASP.NET postback method. Assuming your method returns true, then the button will post. If it returns false then it will not cause a post back.
Does that sound like what you are trying to accomplish?
I think you need a much better understanding of what it means client side and what it means server side and how they all relate together. I've seen more and more developers make a mess of it.
Of course the client side will execute first in your case. Actually there's no way to execute it after the server code is executed (except if you do something manually). I'll try to give a brief explanation:
Whatever you have in your server, will generate some HTML on the client and the user is always interacting on the client. So you have a html button that the user is clicking. What the browser will do is execute the javascript associated with it or if no javascript is specified and the button is a submit button it will submit the form. if you check the generated html you will see that for the onclick event you will have the script you have added followed by some autogenerated script that actually will submit the form to the server. Your server side code will execute only if the page will be submitted.

Resources