How does RequiredFieldValidator automatically stops database being updated? - asp.net

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

Related

Disable Button During Postback With Server-Side Validation

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/

How ASP.NET 4 validation controls work?

I create new page with lots of validation controls, such as RequiredValidation, RegexValidation and so on. I found out that when I create these validation controls, it seems like it render both client java-script and server validation for me automatically.
I want to know, do I understand correctly or not?
Yep. That is correct. The built-in controls do server side validation (for security) and client side validation (for performance and user experience) for you.
Tip: Don't add these validations to the mark-up, but add them through the code behind, as shown in this blog post, since it keeps your code DRY.

How to trigger ASP.NET client-side validations without submit?

I have a website in ASP.NET (WebForms, NOT MVC) which has a survey form divided in several slides. Each slide has a next button that, obviously does a transition (client-side, not post back or remote request) to the next slide.
In each slide I have several ASP.NET controls with their related validators. I want this validators to be triggered when I click the next button (or maybe when each input loses focus?).
I remembered ASP.NET doing client side validation on lost focus, but maybe I'm wrong... (I quit doing ASP.NET development about 3 years now, so I can't remember)
Thanks
UPDATE:
It would be better to make ASP.NET trigger each validator when the associated control lost focus. I remember ASP.NET doing this (or am I dreaming? =P)
First you need to make sure all of your validators have target controls specified using the "TargetControlID" Attribute on the validators.
Then you can set up a validation group per page and specify the group name in your next button and on the controls themselves.
If you are using regular expression validators you can choose them from this website
To Validate Client Side
If you are using custom validators you can create a client function and specify it on the custom validator using the ClientValidationFunction attribute and by setting EnableclientScript = "true" on the custom validator.
Just be sure your client function has sender and args parameters.
It looks like there's a supplied JavaScript function called Page_ClientValidate which should be callable to check the validation manually from JavaScript. I haven't used it, though, so YMMV.
put all your client-side validators into the same validationgroup and with your 'next' button add the same validation group. When you click the button it will automatically trigger all the validators before it does the post-back.
as to manually triggering the validation...
you might also be able to use ValidatorOnSubmit(). I remember doing this in another project but i'm having a hard time finding the code.
It seems that enabling 'SetFocusOnError' on each validator triggers the validation whenever I try to leave the field.
In short decorate your model, now Data Annotations are supported from Asp.Net 4.5
Check my Answer here..Client side webform validations

Using JSON or postback method?

I need to develop a page which has 2 dropdownlist.
Options of dropdownlist 2 are based on selection of dropdownlist 1.
I have 2 methods to change the dropdownlist 2. What will you choose?
1:
Postback when users select dropdownlist 1 and change dropdownlist 2.
Pros:
Can use the postback feature, can use the asp.net validator
Cons:
Need to communicate with server (more traffic)
Users will see the page loading in the status bar.
2:
Get all the data (not very much data) in a JSON object when loading the page and change the dropdownlist 2 using javascript.
Pros:
Don't need to communicate with server(less traffic)
Cons:
Can't use the postback feature and validator and more troublesome to write server validation.
Also, I usually write the JSON object to the page as follows:
var locations = <asp:Literal runat="server" id="litLocation" text="[]" />
And then set the "litLocation" in page_load after the data is processed by datacontractjsonserializer.
Do you do it in the same way?
I prefer the second option, no need to reload the whole page just to refresh one dropdown list. I'd also do the client side dev in jQuery, much easier. You can do the client side validation for the change event of the first dropdown in jQuery as well, and keep the form submit validation in ASP.NET.
Have a look at the selectChain plugin for jQuery (demo's etc here).
Why not have your javascript call the server when the select box is clicked on, using a GET method, and fill in the select box, using json as the response, then, when an option is picked then fill in the second select box with another ajax request.
This would be scalable, in that if you want to add more options you just change the server, and everything is centralized.
You will need to validate when the form is submitted anyway, as it is possible to change a value of a form to something illegal using some debugging tools, such as Firebug, so never trust anything from a webpage until you have validated it.
So, no point worrying about the validation until the form is actually submitted.

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