Upload
riona
View
62
Download
0
Embed Size (px)
DESCRIPTION
Validation Controls, User Controls, Master Pages. IT533 Lectures. Server Controls Validation Controls. A validation control (or validator) determines whether the data in another web control is in the proper format, before the data is processed. - PowerPoint PPT Presentation
Citation preview
IT533 Lectures
Validation Controls, User Controls,Master Pages
Server Controls Validation Controls
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.
JavaScript is a scripting language that enhances the functionality and appearance of web pages and is typically executed 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.
Server Controls Validation Controls
Rich, declarative validationValidation declared separately from input controlExtensible validation frameworkSupports validation on client and serverServer-side validation is always done
Prevents users from spoofing Web Forms
Server Controls Validation Controls
<asp:RequiredFieldValidator>Ensures that a value is entered
<asp:RangeValidator>Checks if value is within minimum and maximum values
<asp:CompareValidator>Compares value against constant, another control or data
type<asp:RegularExpressionValidator>
Tests if value matches a predefined pattern<asp:CustomValidator>
Lets you create custom client- or server-side validation function
<asp:ValidationSummary>Displays list of validation errors in one place
Server Controls Validation Controls
Validation controls are derived from System.Web.UI.WebControls.BaseValidator, which is derived from the Label control
Validation controls contain text which is displayed only if validation fails
Text property is displayed at control locationErrorMessage is displayed in summary
Server Controls Validation Controls
Validation controls are associated with their target control using the ControlToValidate property
Can create multiple validation controls with the same target control
<asp:TextBox id=TextBox1 runat=server />
<asp:RequiredFieldValidator id="Req1" ControlToValidate="TextBox1" Text="Required Field" runat=server />
Server Controls Validation Controls
Page.IsValid indicates if all validation controls on the page succeed
void Submit_click(object s, EventArgs e) { if (Page.IsValid) { Message.Text = "Page is valid!"; }}
Server Controls Validation Controls
Display property controls layoutStatic: fixed layout, display won’t change if invalidDynamic: dynamic layoutNone: no display; can still use ValidationSummary
and Page.IsValidType property specifies expected data type: Currency, Date, Double, Integer, String
Server Controls Validation Controls
Can force down-level option Only server-side validation
http://msdn.microsoft.com/en-us/magazine/bb986074.aspx
<% @ Page Language="c#" ClientTarget="DownLevel" %>
Server Controls Validation Controls
Demo: ValidationControls1.aspxDemonstrates each type of validation control
<configuration> <appSettings> <add key="ValidationSettings:UnobtrusiveValidationMode"
value="none"/> </appSettings></configuration>
Server Controls Validation Controls
The code-behind file validates the information again in case the client has JavaScript disabled.
The submission of a form sends its data to the server and causes the current page to be requested again is called a postback.
The IsPostBack property of class Page determines whether the page is being loaded due to a postback.
The current Page’s Validate method validates the information as specified by the validation controls in the Web Form.
Server Controls Validation Controls
Use the IsValid property of class Page to check whether all the validators succeeded.
You should always call method Validate before using property IsValid.
When data is posted to the web server, the form’s data becomes accessible to the web application through the properties of the various web controls.
Validation Controls requires 'jquery'You will get this error:
WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for 'jquery'. Please add a ScriptResourceMapping named jquery(case-sensitive).
Add the following to web.config configuration:<appSettings> <add key="ValidationSettings:UnobtrusiveValidationMode"
value="none"/></appSettings>
Server Controls Validation Controls
Examining the Client-Side XHTML for a Web Form with Validation If a validation control’s EnableClientScript
property is True, the validator performs client-side validation as the user edits the Web Form. You do not need to be able to create or even understand the JavaScript validation code—the validators are converted to working JavaScript by ASP.NET. The EnableViewState attribute determines whether a web control’s current state is remembered each time a postback occurs.
Server Controls Validation Controls
The default value, True, indicates that the control’s state at the last postback is retained.
A hidden input called __VIEWSTATE stores the controls’ data as an encoded string so the server can determine whether it has changed.
Performance TipSetting EnableViewState to False reduces the amount of data passed to the web server with each request.
Validation Controls Exercise
Validation Controls Exercise
Validation Controls Exercise
Validation Controls Exercise
Master PagesCreating a Master PageThe master page defines the elements we want to appear on
each page. A master page is like a base class in a visual inheritance hierarchy.
The master page contains placeholders for custom content created in each content page.
To create a master page, right click the location of the website in the Solution Explorer and select Add New Item….
Select Master Page and specify Bug2Bug.master as the file name.Master pages have the file-name extension .master and, like Web
Forms, can optionally use a code-behind file to define additional functionality.
Master PagesThe markup for a master page is almost identical to that
of a Web Form. A master page contains a Master directive, which
specifies that this file defines a master page using the indicated Language for any code.
Next, set the title of the page to Bug2Bug.The master page contains two ContentPlaceHolder
controls for content that will be defined by a content page.
Master PagesAt this point, you can edit the master page in Design
mode as if it were an ASPX file. • The ContentPlaceHolder control appears as a
rectangle with a purple outline indicating the control’s type and ID.
• Using the Properties window, change the ID of this control to bodyContent.
Master PagesPlace the cursor to the left of ContentPlaceHolder and
select Table > Insert Table.In the Insert Table dialog, set Rows to 2 and Columns to 1. In the
Layout section, specify a Cell padding and a Cell spacing of 0.Set both the width and height of the table to 100 percent. Make
sure that the Size value in the Borders section is 0.Click OK to create a table that fills the page and contains two
rows.Modify style’s Block category vertical-align property of
the bottom table cell to top and drag the ContentPlaceHolder into this cell.
Modify style’s Position category Height of the top table cell to 130. Add an Image control named headerImage with its ImageUrl property set to the bug2bug.png file.
Bug2Bug.master page that defines a logo image header for all pages
Master PagesCreating a Content PageRight click the master page in the Solution Explorer and
select Add Content Page. Rename the WebForm1.aspx to ContentPage.aspx, then open it in Source mode
The Page directive indicates the MasterPageFile that is used as a starting point for this new page’s design.
The Title property specifies the title that will be displayed in the web browser’s title bar when the content page is loaded.
This value, which we set to Create a New User, replaces the value (i.e., Bug2Bug) set in the title element of the master page.
Because CreateNewUser.aspx specifies Bug2Bug.master as the page’s MasterPageFile, it implicitly contains the contents of the master page.
Master PagesThe content page contains Content controls, in which we
will place page-specific content that will replace the master page’s ContentPlaceHolders.
The ContentPlaceHolderID property of the Content control identifies which ContentPlaceHolder the control should replace
The relationship between a content page and its master page is more evident in Design mode:
Master PagesAdding a CreateUserWizard Control to a Content Page CreateNewUser.aspx is the page in our website that allows first-time visitors to create user accounts.To provide this functionality, we use a CreateUserWizard control.Place the cursor inside the Content control in Design mode and double click CreateUserWizard in the Toolbox to add it to the page. Open the CreateUserWizard Tasks smart-tag menu and click Auto Format. Select the Professional color scheme.Set the CreateNewUser.aspx as the default page by right clicking on it and Set As Start Page.When the user clicks the Create User button, ASP.NET verifies that all the form’s requirements were fulfilled and attempts to create the user account. (we will use this next week)In CreateNewUser.aspx, the Page directive indicates that this content page inherits content from Bug2Bug.master.
CreateUserWizard requires 'jquery'You will get this error:
WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for 'jquery'. Please add a ScriptResourceMapping named jquery(case-sensitive).
Add the following to web.config configuration:<appSettings> <add key="ValidationSettings:UnobtrusiveValidationMode"
value="none"/></appSettings>
Creating ControlsASP.NET provides two ways to create your own
server-side controlsUser Controls: Essentially a mini .aspx fileCustom Controls: You derive a class from System.Web.UI.Control
Creating ControlsUser Controls
User controls simplify the reuse of code and UI components within a Web application
A user control is a user-defined Web server control with an .ascx extension
Contains HTML, but not the <HTML>, <BODY>, or <FORM> tags
Enables full encapsulation Supports nested controlsSeparate code namespaceSeparate code language
Can partition work across multiple developersGreat way to reuse work across multiple pages and
applications
Why Use User Controls?Reuse user interface and code
Page2.aspx
Control1.ascx
Page1.aspx
Page3.aspx
Application A Application B
Adding a User ControlRegisters user control for use on a pageUse the @ Register directive to include a user
control in an ASP.NET Page
Insert the user control in a Web Form
Use Get and Set properties of the user control
<%@ Register TagPrefix="demo" TagName="validNum" Src="numberbox.ascx" %>
<demo:validNum id="num1" runat="server"/>
num1.pNum = 5; //uses Setx = num1.pNum; //uses Get
Example User ControlCreate BeforeUserControl.aspx
Add 2 Textbox controls with RequiredFieldValidator and RangeValidator
Add a Button that adds the values in these textboxes and displays the sum in a Label
Create a Web User Control numberbox.ascxAdd a Textbox controls with RequiredFieldValidator and RangeValidator
Create AfterUserControl.aspxRegister the user control numberbox.ascxAdd 2 numberbox controlsAdd a Button that adds the pNum properties in these numberboxes and displays the sum in a Label
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
Creating ControlsCustom Controls
A class that you createDerived from System.Web.UI.Control
http://msdn.microsoft.com/en-us/library/zt27tfhy.aspx
using System;using System.Web;using System.Web.UI;
public class MyControl : Control { protected override void Render(HTMLTextWriter w) { w.Write(“<h1>Control output</h1>”); }}
Creating ControlsCustom Controls
Must implement Render() methodCan expose properties, methods and eventsShould maintain stateShould handle postback data
Can generate client-side script to do postbackShould handle child controls
Render themHandle events
Can expose and implement templatesCan handle data binding
Creating ControlsCustom Controls vs. User Controls
User Controls Custom Controls
Good for application-specific UI Good for reuse, encapsulate common UI
Easy to build Can be more complex to build
Less flexibility, performance, designer support
Total flexibility, better performance, and designer support
No template support Can support templates