asp.net_ validation Control (class0620)

Source: Internet
Author: User
Tags name database

Why use validation controls

When a user is required to enter data, it is possible for the user to enter information that does not conform to our program's logic requirements, so we validate the input. Client Authentication (user experience, reduce server-side pressure) server-side validation (to prevent malicious attacks, client JS can easily be bypassed) must be the user input data validation, many of these verification logic is repeated, such as the field can not be empty, must be a date format, the number can not be greater than 100, etc. And check both the client and server side.

validation controls

Asp. NET provides the following controls: RequiredFieldValidator: Field Required, RangeValidator: value between the given maximum and minimum value; CompareValidator: Whether a relationship that compares two values satisfies a requirement or is a specified type of data; RegularExpressionValidator: The checksum data satisfies the regular expression; CustomValidator: Custom Validation. Asp. NET provides validation controls that easily implement user input validation, and is not user-browser-independent validation code that runs on the client or server performs a variety of validation controls, which makes validating data easier and easier

RequiredFieldValidator

Function: A non-null validation control that requires the content to be entered ControlToValidate: Sets the control to validate. The ID must refer to the control in the same container as the validation control, which must be on the same page or in the same user control, or must be in the same template as the templated control. If this property is not set, an exception will be cited. To validate an input control, you must apply the System.Web.UI.ValidationPropertyAttribute property to the control. System.Web.UI.WebControls.DropDownList System.Web.UI.WebControls.FileUpload System.Web.UI.WebControls.ListBox System.Web.UI.WebControls.RadioButtonList System.Web.UI.WebControls.TextBox System.Web.UI.HtmlControls.HtmlInputFile System.Web.UI.HtmlControls.HtmlInputPassword System.Web.UI.HtmlControls.HtmlInputText System.Web.UI.HtmlControls.HtmlSelect System.Web.UI.HtmlControls.HtmlTextArea

RequiredFieldValidator

Text property: The error message that is displayed when the validation control is empty. The message can be set to text or you can set the HTML code and JS code errormessage: Provided to the ValidationSummary control, and if the Text property is empty, the value of errormessage is also taken. The display property, which determines how the error message is displayed. Three values: Static: When there is no error message, the control's visiblity style is hidden to hide; Dynamic: The display style of the control is none when there is no error message to implement shadowing. The difference between the two is that the hidden difference between Display:none and Visiblity:hidden is that Visiblity:hidden hidden controls will still occupy space, while Display:none hiding will not occupy space. The display property can also be set to none (used in conjunction with the following ValidationSummary) SetFocusOnError: If the validation does not pass, let the control get the focus InitialValue: Set the default value of the validation control When the client disables JS, the Click button occurs callback, the client authentication is not triggered. Page.IsValid Indicates whether the page verifies that a more secure server-side validation event is successful for client validation failures after the Page_Load event

ComparevalidatoR

Operator properties, comparison operators, selectable values DataTypeCheck, Equal, GreaterThan, Greaterthanequl, LessThan, Lessthanequal, notequal. ValueToCompare, the value to the right of the comparison operator. ControlToCompare, the setting is compared to another control. The Type property is the data type (String, Integer, Double, Date, currency, and so on). Usage one or two control comparison (Demo: compare two times the password entered is the same) ControlToValidate (left of the symbol) ControlToCompare the control to be compared (the symbol to the right) Operator comparison operation type attribute usage two with a fixed value Comparison (Demo: Age must be greater than 18 years old) ValueToCompare Operator comparison Operation Type property

CompareValidator

Usage three-type check (Demo age must be a number) Controltovlidate the control ID of the type to be checked Operator DataTypeCheck type when the control content specified by the validation control is empty, Other validation controls do not, except that RequiredFieldValidator triggers validation. Because we have such a need, in filling out a form, there are mandatory fields are not required, non-mandatory fields can not fill in the value, but if filled, it must be correct. Therefore, unless a validation control other than the null validation control is validated, if it is empty, it will not be checked, whereas if the content is filled, it must be inspected for correctness. So for those older than 18 years and require age to fill this requirement, we will use non-null and compare two validation controls to implement.

RangeValidator

RegularExpressionValidator

RangeValidator Range Validation control (Demo: Train ticket within 10 days) MinimumValue, MaximumValue property: For maximum, minimum type property with Comarevalidator RegularExpressionValidator Regular Expression validation control ValidationExpression regular expression vs provides common regular expressions Demo: ID card QQ Number email address user name between 3-10 bits CustomValidator, custom validation controls. CustomValidator can be used when ASP. NET built-in validation controls do not meet the requirements. Other: CausesValidation: Indicates whether the button submission triggers a grouping of validation validation controls

ValidationSummary

Using the validator error message appears in place of placement, because there are two possible problems: if the form is very large, the user does not see all the error messages, wants to display the error message in the set next to the Submit button, and if the error message is very much error message will be scattered everywhere, hoping to be able to focus on the display. The ValidationSummary control is used to centrally display error messages. Each validation control has errormessage, text two properties, ErrorMessage is used to display values in ValidationSummary, text is used to display values to the validator location, and if text is empty, The errormessage is displayed to both the ValidationSummary and the control's location. The value of the general text is short, because it is displayed directly to the control's position and you know which control it refers to; errormessage to be detailed so that you can read the value from each error message ValidationSummary. ValidationSummary Properties: Diplaymode, display mode, ShowMessageBox Display warning dialog box. ShowSummary Display Error Summary validation control's Display:none, error message is displayed only in the rollup control

Practice

Exercise: Implement the registration page (write check logic on the line): User name (required, length must be between 3-10), password (required, length between 3-9), re-enter the password (must be the same as the password), the mailbox (optional, must comply with the mailbox format), entry date, graduation date (required, with TextBox, Graduation date is greater than the entry date, less than the current date), gender (with DropDownList, required, select: "Please select gender", "male", "female", "confidential"), Birthday month (required, textbox), Day (required, textbox, Verify that the value of the day in the date is within the legal range, {1,3,5,7,8,10,12} is 31 days, {4,6,9,11} is 30 days, February assumes the maximum fixed is 29 days regardless of leap year common year. , CustomValidator). Common problem? How do I use validation controls in Ajax? Trigger RangeValidator and length of non-null validation controls and validation controls must be placed in the same template

Page_clientvalidate//causes all validation controls on the page to perform client-side validation validatorvalidate//perform validation methods for a validation control Page_isvalid property C:\WINDOWS\Microsoft.NET \framework\v2.0.50727\config Global profile machine.config Web. config If there is a validation control on a page, when the point submits the button, the procedure is as follows: (in the case of the client cannot disable JS script) 1) on the client , call the validation method for each validation control on the page 2) if all validation controls on the page are successful after the client's validation, the data is submitted to the server. 3) Execute the Page_Load method on the server side, execute the server-side validation method of all validation controls, and then execute the Click event of the Submit button Controltovalidator > Controtocompare

Navigation Controls and Masters

Navigation controls:

Give the user a map that can indicate their current location to facilitate the user to jump to the traditional implementation: the Include file user control hard-coded in ASP. Provides a breadcrumb navigation control SiteMapPath need to provide a sitemap site map is based on XML format The file name of the Sitemap must be: Web.sitemap TreeView General Use the tree menu navigation on the left can be based on an XML file or you can write code to manipulate menu general navigation with menus

Why do I need a template

The layout of the site is usually unified, above the logo, menu, the following is the company address, copyright notice. If each page repeats these functions: repetitive labor, once modified, each page is modified. can use FRAMESET (FRAMESET) technology to solve, but frameset technology is not flexible, and it is difficult to SEO, so only part of the intranet system is still in use frameset,. NET in general with Master (MasterPage) technology to solve this problem. MasterPage is such a technology, the page layout is good, in the change of content part "blank", the blank part of the page to fill the content, this page as long as the fill in the blanks, without repeating the design page structure, once you want to modify the page structure to modify the master page, so that all the pages will change. Master page "Dig Pit", specific page "pits". The master page, the specific page can use almost all the ordinary WebForm page can use the technology.

Add a master page, use <asp:ContentPlaceHolder> dig pits, the new master page has been automatically set up with two ContentPlaceHolder, and you can add more ContentPlaceHolder. Add some script to the front of id= "head" and add some content before and after Id= "ContentPlaceHolder1". Create a specific page that uses the master page, website the new Web form, tick Select Template page, webapplication new Web content form, and then select the master page to use for the page (you can create multiple master pages in one project, such as a news channel with a master page , and a different master page for the video channel). The difference between using the master's specific page and the normal ASPX page is that the @Page area uses the MasterPageFile property to indicate which master page the page is using, that the page does not contain content such as HTML, and that only the contents of these pits are defined <asp:content. <asp:Content> is used to pits the master page in a specific page, ContentPlaceHolderID this Content to fill in which pit in the master page corresponds to the ContentPlaceHolder ID in the master page

The specific page can be pits to the master page or not pits, if not pits the default content defined in <asp:ContentPlaceHolder> is displayed. Case: Implementation on the navigation menu, under the copyright notice, the left functional panel, the right side for the specific content of the template, and then implemented separately about us and the login interface. When you use hyperlinks, picture addresses, and so on in a master page, you need to be aware of the path problem, and the link address, picture address, and so on of the Runat=server control in the master page will be resolved to the address of the master page. The client HTML control, the ASP. NET engine, is output directly, so it resolves to a specific page address. It is recommended that you use the server-side controls, and if you cannot use them, you can call Resolveclienturl, ResolveUrl in the ASPX page to set different headings for each specific page of the virtual path, as long as you set the Title property in the @page of the specific page. You can locate controls in a master page by Master.findcontrol in a specific page and then manipulate controls in the master page, such as hiding a control in a master page in a specific page.

three-tier architecture (3-tier application)

The three-tier architecture (3-tier application) typically has a three-tier architecture that divides the entire business application into: The presentation layer (UI), the Business Logic layer (BLL), the data Access Layer (DAL).   1, the presentation layer (UI): Popular speaking is to show the user interface, that is, users in the use of a system when he saw the gains.   2, Business Logic Layer (BLL): The operation of the specific problem, it can be said that the operation of the data layer, the data business logic processing. 3, data access Layer (DAL): This layer of transactions directly manipulate the database, for data additions, deletions, modifications, updates, lookups and so on. Pet Store (Pet Shop) Microsoft Showcase. NET Enterprise development paradigm and Sun's petstore business competition a small e-commerce case embodies the development idea and design concept of Microsoft to promote 22 projects, the classic system, from the idea of design to the best coding, learning reference value is very high

Advantage 1, the developer can only focus on the entire structure of one of the layers, 2, can easily replace the implementation of the original level with the new implementation, 3, conducive to standardization, 4, conducive to the reuse of the logic of each layer. 5, more safety shortcomings 1, reduce the performance of the system. This is self-evident.   Without a tiered structure, many businesses can access the database directly to get the data, and now they have to do it through the middle tier. 2. Sometimes cascade changes are caused. This kind of modification is especially reflected in the top-down direction. If you need to add a feature in the presentation layer to ensure that the design conforms to a layered structure, you may need to add code to the appropriate business logic layer and the data access layer, because the UI layer does not allow direct access to the DAL layer. 3, increase the development cost

Three-tier architecture creation

Create four projects, the presentation layer project type is WebApplication, the business logic layer, the data access layer, the model layer are the class library. Add Reference: The presentation layer refers to the business logic layer. The business logic layer references the data access layer. Because the model layer is responsible for passing data between layers three, each layer refers to the model layer. Sometimes there will be a public project, each layer will be quoted. Model Layer (ORM): Each table in the database creates a class at the model level, with the same name as the data table name, and if the table name in the database is a complex type, the generic model layer class name is singular. The fields in the table are built into the properties of the class. Database access layer: Each class of the model layer corresponds to a class in the database access layer, which is typically named +services the class name in the model layer, which contains only crud methods for that table. Business Logic Layer: The class name in the business logic layer is determined by the business, in general it can also correspond to the class of the data access layer, and the class name is usually named +manager the table name. Presentation layer: A method of invoking the business logic layer, consisting of a requirement Web page. This layer generally does not appear in the SQL statement related content, even if it appears, can not appear to execute the SQL statement.

Design tables based on requirements

A hotel in order to improve management efficiency, the use of a new computer network and information management system, infrastructure and business processes to intelligent control. "Infrastructure" is used to initialize room type, room rate, room information, etc. 1, "Room type setting" is used to set the category information of the room, including the category name, the price of the category, whether the extra bed, the extra bed price, notes, etc. 2, "Room information settings" To set the initial information of the room, including room number, Room category, room status, number of beds, number of guests, description, etc.

The processing of foreign key in model layer

Two ways: Add state ID property for entity class, store state ID add state attribute to entity class, store state object Demo: Demonstrates how to create a three-tier structure Project Demo: Create a three-tier structure project with dynamic soft

GridView, DataList, DetailsView

Two methods of data binding

Method One: After the data is obtained, assign the DataSource property, and then execute the control's DataBind () method. Demo:dropdownlist Data binding Method Two: Use a data source control to assign a DataSourceID to a data-bound control. DataSource properties and DataSourceID cannot be used at the same time. If you first use the data source control to obtain data and bind the display, in the program you need to use manual binding method to display the data, you must first assign NULL to DataSourceID

Use of the GridView 1

AllowPaging property: Automatic Paging AutoGenerateColumns property: Whether to automatically generate columns pageindex properties: Current page pagesize properties: Page Size Rows Property: Collection of data rows displayed Editindex Properties: Refers to the row that the user is editing, and if no rows are edited, the use of the optional field in the 1 column setting is set to: BoundField: Displays the data to be bound CheckBoxField: shown in a checkbox, typically tied to a bit type in the database HyperLinkField: Displayed as hyperlinks, the general link address is related to bound data ImageField: Display as a picture, general picture address and bound data is related ButtonField: Display CommandField as a button: Contains the ability to trigger additions and deletions to change the button, in fact, is a normal button, the difference is the CommandName settings.

CommandName Update Events RowUpdating and RowUpdated events are triggered for update, to be set in this event Editindex CommandName the Cancel Event Rowcancelingedit event after the edit of the cancel trigger point to set the Editindex=-1 in this event CommandName Delete Events rowdeleting and rowdeleted events for delete if automatic paging is enabled, Allowpaging=true, when you click the previous page and the next page, When the Pageindexchanging event is triggered, you set the pageindex in this event

If you use the manual binding method, the update and delete operations are written in their triggered ing event. If a data source control is used to bind, the data source control automatically calls its specified update and delete method after the update and delete ing events are triggered, and then the Ed event is triggered. Can be based on the Ed event in E. Exception property to determine if there was an error during the update and delete process. The GridView efficient paging, in fact this function is provided by the data source control, set the following properties: Enablepaging=true; Enable data source paging MaximumRowsParameterName StartRowIndexParameterName SelectCountMethod SelectMethod Delete two parameters of auto-generated selectparameters

DataList and DetailsView

DataList: Typically used only to display data, he can only implement data binding by setting up a template. DataList does not support sorting and paging, so the pagination and sorting methods are shown in the following case. DetailsView: Typically used to display a piece of data, but also to implement updates and inserts. Often used in the main fine table. Comparison between data source controls: Efficiency: Gridview<datalist<reapter GridView is typically used to display data in a grid (table). DataList is used to display data in an HTML customization (template) Reapter data binding does not produce any code that is not in the template, so commonly used in div+css page layouts or bindings generate XML files similar to the FormView and DetailsView. The former to customize the layout, the latter is generally used to fix the layout

Cache

Full page cache 1) Browse frequently 2) Web pages that do not update for a short period of time require a large number of computed webpages based on the control cache: VaryByControl based on the parameter cache: VaryByParam replaces the application-level cache after the full-page cache is partially cached: Database-dependent caching. Based on wheel Xun and notification test: Unit test Web Test load test

Website release

Database

Attach detach backup Create one user for each app modify connection string c/S app. Config

Configuration file

Asp. NET Machine.config: Provides the default configuration for the entire machine, and changes to that file will affect all native site Web. config: Typically used for application-level configuration files, with modifications that do not affect other sites, or for subdirectory profiles under sites Based on XML, configuration section elements are case-sensitive, readable and writable (compared to binary configuration convenience) after the configuration is modified, ASP. NET automatically detects changes without requiring a manual restart of the server or IIS

Configuration file (Nearest principle

Security verification

Security control authentication, verifying that users have the appropriate identity rights control, control the permissions that are owned by users of various identities authentication methods for Windows Authentication Passport authentication forms authentication <system.web> < Authentication mode= "Forms" > <forms name= "AdminUser" loginurl= "~/admin/adminlogin.aspx" timeout= "All" > </ Forms> </authentication> </system.web>

Authorization and refusal

Authorize allow, deny, deny special symbol: "*" on behalf of all users, "? "On behalf of anonymous users <system.web> <authorization> <deny users="? /> <allow roles= "admin" > <deny users= "*"/> </authorization> </system.web>

Configuration file

Custom error page: <customerrors mode= "RemoteOnly" defaultredirect= "errorpage.htm" > <error statuscode= "404" redirect= "Filenotfound.htm"/> </customErrors> allow debug <compilation debug= "true"/> Application Runtime configuration

Server Configuration

Install IIS First, then dotNetFramework aspnet_regiis ftp serv-u

Publishing Web Sites

Compile build Release version publish site modify config: compilation set to false modify connection string customErrors request domain name and purchase server or virtual host to resolve domain name to server, note: Resolution is not effective immediately, are not synchronized. Attach a website domain name on the server to upload the Web site to the server attached database

Publishing Web Sites

If you are a server, also pay attention to the following problem: Upload folder does not give Execute permission: In IIS Manager found the upload folder, select the Properties--execute permissions, set to "none". This makes it impossible to upload executable code to the upload folder, even with the exploit. Remove browse permissions for all folders, prevent users from viewing the list of files in the Web site, locate the master node in IIS Manager → properties → home directory → cancel directory browsing. Background folders only allow Administrator IP access, folder → properties in IIS management, Web server Extensions, only allow ASP., other CGI, ASP and so on all prohibit.

Cache dependency

Dependent on the contents of the file CacheDependency CDEP = new CacheDependency (FilePath); dependent on database content (polling mechanism/notification mechanism) One: polling mechanism 1. Create a new version table in the database. 2. Create a new trigger on the database (such as new on the news sheet). 3. Use Aspnet_regsql.exe in C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727: Register: Aspnet_regsql-s. -E-ED-D database name-et-t version table name deleted: Aspnet_regsql-s. -E-D database name-dt-t version table name cancels database cache dependency: Aspnet_regsql-s. The-E-DD database name database is listed as the registered table: Aspnet_regsql-s. -e-d database name –LT4. Configure Web. config (see note) 5. Database Dependent object SqlCacheDependency CDEP = new SqlCacheDependency ("Gssms", "CACHEDEP");

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.