Validation in a WebForms application - asp.net

I'm working on a WebForms application that consists of a number of pages and each page contains a form which the user fills out. Each form corresponds to a part of an entity meaning that the data from one page/form populates a part of the entity's fields or its child entities' fields.
As an example: a Person's name and birth data is filled out on first page, health status on second page, family information on third page etc.
The data should of course be valid before continuing to the next page. My customer doesn't want to deal with jQuery or Javascript so this is ruled out. What is "best practice" for implementing validation in this case?
Entity Framework 4 is being used and most of the GUI controls are implemented in HTML and not by WebForms controls.

If you're using custom HTML for your inputs, then you're probably going to have to use some custom code for your validation. In your server-side form handler you can validate the inputs and render the page back to the user if something was invalid. The input checking could be as simple as:
if (string.IsNullOrWhiteSpace(FormCollection["someRequiredInput"])
You can iterate through all of your inputs, check them according to business logic, and perhaps build a list of errors. Then after the input checking, if the list of errors isn't empty, render the page back to the user with the errors added to a placeholder of some kind. If the list is empty, continue processing the form post.
Even if JavaScript wasn't ruled out, you'd still want to perform server-side validation. Never assume that the client-side code worked as intended or was even executed at all. Client-side validation isn't a security measure, it's just a better user experience. Server-side validation is the only real validation.
(So you may still be able to add client-side validation for that added UX touch, and if the client does indeed disallow JavaScript then they wouldn't see that and would just use the server-side validation instead. This is sometimes referred to as "graceful degradation" where you design a web application to still fully function, albeit with slightly less UX goodness, when the user disables client-side technologies.)

My customer don't want to deal with jQuery och[sic] Javascript so this is ruled out.
Good. Javascript is the wrong place to enforce validation. Any validation you do with javascript is merely a performance optimization. The only acceptable place to truly validate data is on the server.
That out of the way, .Net includes some handy Validation controls you can use. One of those controls is a CustomValidator, that is very easy to override and provide your own server-side code to enforce whatever rules you want. If you're using webforms, these controls are an obvious choice.
Since you have a multi-paged approach, you may also want to look into the Wizard control.

Related

Server-side validation within an ASP.Net User Control

I'm trying to get some User Controls I'm writing to perform their own server-side validation, checking the database to ensure that certain criteria are valid. In one case the control doesn't even accept any input, it just displayed some information based on database state.
I know the ASP.Net has its own validation framework, and I'm keen not to re-invent the wheel. However, I'd like the controls to check whether they're valid themselves (that seems more object oriented to me), rather than having to create custom validators on every page on which I place the controls. I've had a quick look at the IValidator interface, but this seems to be targeted at Validators, rather than the controls themselves. It seems cleaner to me to have the control itself check the entered data (where appropriate) and database state and report whether or not it is valid.
Is this possible in ASP.Net without re-writing the whole of the ASP.Net validation framework, or am I just trying to go about this in completely the wrong way?
It turns out I was close with the IValidator stuff, just missing the link to the Page.Validators collection. Here's a fully worked example:
http://www.codeproject.com/KB/custom-controls/selfvalidatingtextbox.aspx
Hard to believe how much time I spent looking for this yesterday!

User error reporting in ASP.NET

I want to build user friendly error reporting. Wrong input, db connection errors and such.
Problem is i need the same module be implemented for 3 different systems and to use jQuery UI modal boxes for UI.
when i redirect to another page ie.
db connection error i redirect to
error page
when i use return to same page ie.
input value 1 bigger than value 2
when it should be other way around
ASP.NET Ajax UpdatePanel errors,
wrong input for controls within
UpdatePanel that doesn't do regular
postpacks.
thanks for any help with implementation...
To clarify my question
I don't need input or object validation framework. I use ASP.NET and my own business logic to validate on client and server side.
what i really need is
Help with constructing a class that will show errors to users, current process is i catch exception, wrong input value or wrong link and based on that show user friendly message. I have no time and interest in learning logging framework as from my short experience to configure any pre-made high level framework (low level to me is ASP.NET) is harder that to have your own business logic and sometimes requires application re-design...
anyways... My question is pretty clear above. I need way to show centralized messages using jQuery UI.
When i redirect to another page i can save error in Session and get it on other page, if i use return to same page i cannot use Session and had no luck with overriding MasterPage public variables. When i have Ajax UpdatePanel i want again to validate data and show jQuery UI modal...
thats all
A different tactic would be to perform some validation on the client and since you are using jQuery there is a nice form validation plugin called Validation. Here is a good demo page. This will block you post back to the server until you have appropriate data types supplied for you form and will work with your Ajax update panels as well.
With this plugin your HTML mark up is quite straight forward:
<form id="theForm">
<input id="startDate" type="input" class="required datetime"/>
</form>
This will eliminate the need to direct to Error.aspx, store session variables, etc.
For those error that occur on the server, you need to consider whether the user should be able to progress further should a DBConnection error be thrown. In that case you could redirect to your error page, inject your error text and have the client display the content in the jQuery dialog box.
Edit: Are you logging exceptions to a database? If not I would recommend at least a rudimentary log. Other alternatives would be logging to a rolling file appender using log4net. Then, you can load the appropriate error from the logs for display to the user, regardless of how and where you are displaying the error.
See log4net
Also, a not of caution: Don't display DB connection errors to users. Log them so that you know whet is going on and then just tell the user that an error has occurred and that you are aware of it and looking into it.
End Edit
One good way to validate input is to put the validation on your data classes. This allows you to validate them at any time. I know this doesn't solve your redirection scenario which is more of a workflow issue and I hope some others can help you with that.
The reason I mentioned putting input validation on your data classes is that it allows you full control over when your validation is called and it allows you to validate multiple times, on the Client Side and Server Side for example.
A good implementation of this is the FluentValidation framework, which can be extended to automatically generate clientside validation, using the JQuery Validation plugin.
Another option which is becoming popular is Data Annotations. I don't have experience with these yet, but they are worth searching for with your favourite search engine.

ASP.NET AJAX Validation Controls

I use the ASP.NET validation controls in an ASP.NET web forms environment. Is the better approach to keep all of the validation rules server-side, such as using AJAX to validate a field, without posting the whole page back.
I found one control called ValidatorCallout ( http://www.asp.net/ajax/ajaxcontroltoolkit/samples/ValidatorCallout/ValidatorCallout.aspx ) but was trying to figure out if there was a better approach.
You should always perform Server side validation, regardless of whether you do any client side validation. This is because there are many ways around clientside validation, such as switching js off or sending a custom built request that doesn't use your page.
It is a good goal to use the same validation rules on both client and server. xVal is a good option for this.
A really good example of this is how I hacked a certain Airline website for our trip to Dubai. When I was trying to select a special meal for my daughter, who is under two years old, there was no "child" option in the select list. Apparently, child meals are only available if you are older than 2. There was a child option for my older daughter. So I opened Firebug, added the option, selected it and submitted the form. It was accepted.
On the flight two child meals turned up as ordered.
Damn! Come to think of it, I should have changed it to First Class! Not on the ball, Mr Dyson!

Is is possible to get ASP.NET input controls to act like a basic HTML Form?

ASP.NET has a number of nice features regarding making data input pages:
Adding input controls is easy (<asp:...).
The system automatically generates member variable for the controls.
Post-backs automatically populate the members variable with the returned values.
and some not so nice bits
post-backs seem to be tied to JavaScript for even the simplest of cases. For instance, with statically defined pages, using only basic controls, that are known at compile time.
My questions:
Is is possible to get the first list without the second?
What features does that JavaScript give the user?
What does that JavaScript actually do?
What is the technical reasons that it's used even in trivial cases?
As it happens my assumption were in error: See here
It really depends on the types of controls you are trying to use here -- the only ones that implement javascript are those that can't natively cause a postback (ie, an input/submit button are the only two that can). If you are using a LinkButton, ImageButton, or anything that you set "AutoPostBack = true" on will turn javascript on in order to cause a postback.
Other controls can also potentially use javascript if they are more advanced such as the Calendar. The technical reason for using javascript here is to provide automated postback when the controls require more advanced server interaction -- think about it, a link is meant to only ever be a link and if we're trying to make it operate as a button we have to force it to do just that through javascript interaction.
So that being said, yes you can definitely use ASP.NET without it having javascript you just have to avoid the controls that implement it by including functionality you couldn't possibly have without it. You can just as easily add HTML controls and add the runat="server" attribute and gain member variables to the control from code-behind.
Here's what came to my mind:
What features does that JavaScript give the user?
Client side validation.
What does that JavaScript actually do?
For exmaple, it ensures that the correct (server-side) event handlers are called, by setting the __EVENTTARGET hidden field.
Is is possible to get the first list without the second?
You can use normal HTML controls instead of the ASP.NET controls. Then on the server-side, you can read the control's values from the Form collection.
I assume you mean the javascript associated with an <asp:Button /> control, right?
In addition to the reasons mentioned by Fooberichu, the javascript can also help with ASP.NETs client side validation framework.
But I think it's primary use is to alert the framework what events it should fire on the postback in the page behind.
So if you had two buttons on the form, SaveButton and DeleteButton, the javascript helps the framework know whether it should execute the SaveButton_Click event or DeleteButton_Click event.
Hope this helps.

Understanding Postbacks in ASP.NET

For example,
If I have a textbox with runat=server on a page, The value will be posted back to the server so I can access the properties in the code-behind.
However, under the following situations, does it still hold true?
A textbox with runat=server but does not appear in the function that is post back to. For example, a button is also on the page, when clicked a post back occurs and within the method that is raised, this textbox was not used.
Within a MasterPage, will a textbox residing on the Masterpage itself be posted back?
Because just thinking, isn't this mechanism bloated in nature?
If all input controls and its value are posted back on every single button click (even when the input control is not needed), doesn't this deteriorate performance?
Having just one Form Tag on the page really restricts us to using this mechanism?
Truly Understanding ViewState is a must read article on the subject of ASP.NET ViewState
There are several options to cut down on the bloat (and yes, there's a lot of it when dealing with lots of controls):
Use AJAX to post only the items required - although be careful to allow clients that don't have JavaScript enabled to still use the page/ site.
The MVC framework allows multiple form tags to be used so you can group sections if needs be.
Set the EnableViewState to false on pages/ controls.
Break up your pages into smaller ones.
Additionally, check out this brilliant graphical representation of the Page Life Cycle in ASP.NET.
Every input on the page is posted back fully unless you use ajax, because of the single form tag. Welcome to asp.net...
As long as the method that you're hitting on the server-side is a non-static member of the page's class, it'll have access to the textbox and all other controls on the page.
And yes, all controls rendered to the browser (whether in the MasterPage, user control, etc.) will be available on post-back.
You may want to look into Understanding ASP.NET View State.
There surely are performance hits with this architecture, but (depending on complexity of the page) it's usually not an issue from the server load perspective, because hardware upgrades are typically cheaper than additional programming hours spend on optimizing application performance.
With that said, (and as others have pointed out) look into using AJAX if you want to avoid whole page-level postbacks to the server.
Yes, it's all posted back, and yes it can cause bloat. I'm sure if you search for ViewState you will find plenty of people ranting about it and how to minimise it :)
Yes your text box will be available in both cases, yes it is bloated. This is where AJAX comes into play. Using AJAX you can send just the data you need.
If you want to send a minimal ammount of data, you could use a Page Method (static method on page decorated so the script manager builds javascript to call it or you could call it using jquery or other methods), or a script enabled web service works nice as well.
You also have viewstate which can get very large. ASP.Net MVC is a new paradigm instead of using WebForms which doesn't have view state, or post backs. It embraces HTTP instead of hidding it giving developers more control.
The textbox data would be posted back as noted. In addition to using Ajax, disabling view state greatly imporoves your page's performance though even then data in properties critical to the functioning of controls (Control state) would still be posted back.
If you didn't have postback for every control on the form, you wouldn't be able to access it in code-behind. I.e. if in your button press you wanted to modify the property of the text control you couldn't do that because ASP.Net would know nothing about the text control.
Since the communication between the server and the client is stateless and every time a page is server the server forgets all about it Postbacks are important if you want to work with the same page again. No matter what programming language you use, this or similar mechanism exists for processing server side code.
If you wish to minimize postback (viewstate size), do this.
Set enableviewstate=false on all controls that you don't want posted back.
Use AJAX and web services wherever possible (and don't use UpdatePanel).
Use HTML control as much as possible instead of ASP.Net controls.
Hmm.. There are some excellent suggestion in other answers and good links too.
You've pretty much hit the nail on the head with vanilla ASP.NET - it's not very good! In both the instances you describe the answer is yes - the textbox will be sent with the form.
The whole postback/ViewState problem is a bit of a pain, one of the first things any competent ASP.NET developer learns to do is avoid them!

Resources