how to put validation in asp.net

Download How to put Validation in Asp.net

If you can't read please download the document

Upload: apex-tgi

Post on 18-Jun-2015

479 views

Category:

Technology


3 download

DESCRIPTION

A validation control (or validator) determines whether the data in another web control is in the proper format, before the data is processed. When the XHTML for our page is created, the validator is converted into JavaScript that performs the validation.

TRANSCRIPT

  • 1. Validation Controls, UserControls,Master Pages

2. Server ControlsValidation Controls A validation control (or validator) determines whetherthe data in another web control is in the proper format,before the data is processed. When the XHTML for our page is created, the validator isconverted into JavaScript that performs the validation. JavaScript is a scripting language that enhances thefunctionality and appearance of web pages and is typicallyexecuted on the client. Because some clients disable or do not support scripting,ASP.NET validation controls can function on the client,on the server or both. 3. Server ControlsValidation Controls Rich, declarative validation Validation declared separately from input control Extensible validation framework Supports validation on client and server Server-side validation is always done Prevents users from spoofing Web Forms 4. Server ControlsValidation Controls Ensures that a value is entered Checks if value is within minimum and maximum values Compares value against constant, another control or datatype Tests if value matches a predefined pattern Lets you create custom client- or server-side validationfunction Displays list of validation errors in one place 5. Server ControlsValidation Controls Validation controls are derived fromSystem.Web.UI.WebControls.BaseValidator, which isderived from the Label control Validation controls contain text which is displayed only ifvalidation fails Text property is displayed at control location ErrorMessage is displayed in summary 6. Server ControlsValidation Controls Validation controls are associated with their targetcontrol using the ControlToValidate property Can create multiple validation controls with the sametarget control 7. Server ControlsValidation Controls Page.IsValid indicates if all validation controls onthe page succeedvoid Submit_click(object s, EventArgs e) {if (Page.IsValid) {Message.Text = "Page is valid!";}} 8. Server ControlsValidation Controls Display property controls layout Static: fixed layout, display wont change if invalid Dynamic: dynamic layout None: no display; can still use ValidationSummaryand Page.IsValid Type property specifies expected data type:Currency, Date, Double, Integer, String 9. Server ControlsValidation Controls Can force down-level option Only server-side validation http://msdn.microsoft.com/en-us/magazine/bb986074.aspx 10. Server ControlsValidation Controls Demo: ValidationControls1.aspx Demonstrates each type of validation control 11. Server ControlsValidation Controls The code-behind file validates the informationagain in case the client has JavaScriptdisabled. The submission of a form sends its data to theserver and causes the current page to berequested again is called a postback. The IsPostBack property of class Pagedetermines whether the page is being loadeddue to a postback. The current Pages Validate methodvalidates the information as specified by thevalidation controls in the Web Form. 12. Server ControlsValidation Controls Use the IsValid property of class Page tocheck whether all the validators succeeded. You should always call method Validatebefore using property IsValid. When data is posted to the web server, theforms data becomes accessible to the webapplication through the properties of thevarious web controls. 13. Server ControlsValidation ControlsExamining the Client-Side XHTML for a Web Formwith Validation If a validation controlsEnableClientScript property is True, thevalidator performs client-side validation as theuser edits the Web Form. You do not need to be able to create oreven understand the JavaScript validationcodethe validators are converted to workingJavaScript by ASP.NET. The EnableViewState attributedetermines whether a web controls current stateis remembered each time a postback occurs. 14. Server ControlsValidation Controls The default value, True, indicates that the controlsstate at the last postback is retained. A hidden input called __VIEWSTATE stores thecontrols data as an encoded string so the server candetermine whether it has changed.Performance TipSetting EnableViewState to False reduces the amount of datapassed to the web server with each request. 15. Validation Controls Exercise 16. Validation Controls Exercise 17. Validation Controls Exercise 18. Validation Controls Exercise 19. Master PagesCreating a Master PageThe master page defines the elements we want to appear oneach page. A master page is like a base class in a visualinheritance hierarchy.The master page contains placeholders for custom contentcreated in each content page.To create a master page, right click the location of the website inthe Solution Explorer and select Add New Item.Select Master Page and specify Bug2Bug.master as the filename.Master pages have the file-name extension .master and, like WebForms, can optionally use a code-behind file to define additionalfunctionality.Leave the box labeled Place code in a separate file uncheckedand click Add to create the page. 20. Master Pages The markup for a master page is almost identical to thatof a Web Form. A master page contains a Master directive, whichspecifies that this file defines a master page using theindicated Language for any code. Code that would usually be placed in a code-behind filecan be placed in a script element. Next, set the title of the page to Bug2Bug. The master page contains two ContentPlaceHoldercontrols for content that will be defined by a content page. 21. Master Pages At this point, you can edit the master page inDesign mode as if it were an ASPX file. The ContentPlaceHolder control appears as arectangle with a purple outline indicating the controlstype and ID. Using the Properties window, change the ID of thiscontrol to bodyContent. 22. Master Pages Place the cursor to the left of ContentPlaceHolder and selectTable > Insert Table. In the Insert Table dialog, set Rows to 2 and Columns to 1. In theLayout section, specify a Cell padding and a Cell spacing of 0. Set both the width and height of the table to 100 percent. Make surethat the Size value in the Borders section is 0. Click OK to create a table that fills the page and contains two rows. Change the style to have vertical-align property of the bottomtable cell to top and drag the ContentPlaceHolder into this cell. Set the Height of the top table cell to 130. Add an Image controlnamed headerImage with its ImageUrl property set to thebug2bug.png file. 23. Bug2Bug.master page that defines a logoimage header for all pages 24. Master PagesCreating a Content Page Right click the master page in the Solution Explorer andselect Add Content Page. Rename the Default.aspx toContentPage.aspx, then open it in Source mode The Page directive indicates the MasterPageFile that is used asa starting point for this new pages design. The Title property specifies the title that will be displayed in theweb browsers title bar when the content page is loaded. This value, which we set to Create a New User, replaces thevalue (i.e., Bug2Bug) set in the title element of the master page. Because CreateNewUser.aspx specifies Bug2Bug.master asthe pages MasterPageFile, it implicitly contains the contents ofthe master page. 25. Master Pages The content page contains Content controls, in which wewill place page-specific content that will replace the masterpages ContentPlaceHolders. The ContentPlaceHolderID property of the Contentcontrol identifies which ContentPlaceHolder the controlshould replace The relationship between a content page and its master pageis more evident in Design mode: 26. Master PagesAdding a CreateUserWizard Control to a Content Page CreateNewUser.aspx is the page in our website that allowsfirst-time visitors to create user accounts. To provide this functionality, we use a CreateUserWizardcontrol.Place the cursor inside the Content control in Design mode anddouble click CreateUserWizard in the Toolbox to add it to the page.Open the CreateUserWizard Tasks smart-tag menu and click AutoFormat. Select the Professional color scheme.When the user clicks the Create User button, ASP.NET verifies thatall the forms requirements were fulfilled and attempts to create the useraccount. (we will use this next week)In CreateNewUser.aspx, the Page directive indicates that thiscontent page inherits content from Bug2Bug.master. 27. Creating Controls ASP.NET provides two ways to create yourown server-side controls User Controls: Essentially a mini .aspx file Custom Controls: You derive a class fromSystem.Web.UI.Control 28. Creating ControlsUser Controls User controls simplify the reuse of code and UIcomponents within a Web application A user control is a user-defined Web server control with an.ascx extension Contains HTML, but not the , , or tags Enables full encapsulation Supports nested controls Separate code namespace Separate code language Can partition work across multiple developers Great way to reuse work across multiple pages andapplications 29. Why Use User Controls?Reuse user interface and codeControl1.ascxPage2.aspxApplication A Application BPage1.aspxPage3.aspx 30. Adding a User Control Registers user control for use on a page Use the @ Register directive to include a usercontrol in an ASP.NET Page Insert the user control in a Web Form> Use Get and Set properties of the user controlnum1.pNum = 5; //uses Setx = num1.pNum; //uses Getnum1.pNum = 5; //uses Setx = num1.pNum; //uses Get 31. Example User Control Create BeforeUserControl.aspx Add 2 Textbox controls with RequiredFieldValidator andRangeValidator Add a Button that adds the values in these textboxes anddisplays the sum in a Label Create a Web User Control numberbox.ascx Add a Textbox controls with RequiredFieldValidator andRangeValidator Create AfterUserControl.aspx Register the user control numberbox.ascx Add 2 numberbox controls Add a Button that adds the pNum properties in thesenumberboxes and displays the sum in a Label 32. Creating ControlsProgrammatic Use of User Controls Page.LoadControl(string source) Dynamically instantiates a user control Create an instance:Control numbox1 = Page.LoadControl("numberbox.ascx"); Insert into the control hierarchy:myPanel.Controls.Add(foo); CreateDynamicUserControls.aspx 33. Creating ControlsCustom Controls A class that you create Derived from System.Web.UI.Controlusing System;using System.Web;using System.Web.UI;public class MyControl : Control {protected override void Render(HTMLTextWriter w) {w.Write(Control output); http://msdn.microsoft.com/en-us/library/zt27tfhy.aspx}} 34. Creating ControlsCustom Controls Must implement Render() method Can expose properties, methods and events Should maintain state Should handle postback data Can generate client-side script to do postback Should handle child controls Render them Handle events Can expose and implement templates Can handle data binding 35. Creating ControlsCustom Controls vs. User ControlsUser Controls Custom ControlsGood for application-specific UI Good for reuse,encapsulate common UIEasy to build Can be more complex to buildLess flexibility, performance,designer supportTotal flexibility, better performance,and designer supportNo template support Can support templates