Scott Mitchell's ASP. NET 2.0 data Tutorial: Add verification controls on the edit and insert Interfaces

Source: Internet
Author: User

Original Text | download the encoding example in this tutorial | download the PDF version of this tutorial

Introduction

So far, the tutorial on editing DataList does not contain any input to verify the user. Even if the user does not input the product name or the negative price, an exception may occur. In the previous chapter, we learned how to add Exception Handling Code to DataList's UpdateCommand event processing to capture exceptions and display friendly error messages. However, the ideal editing interface should contain verification controls to prevent users from entering illegal data in the first place.

In this chapter, we will learn how to add verification controls in EditItemTemplate of DataList to provide a safer editing interface, which is very easy. This chapter uses the example created earlier and the extended editing interface to add appropriate verification controls.

Step 1: Process abnormal replication examples of BLL and DAL

In The BLL and DAL handling exceptions, we created a DataList that lists the product name and price in two columns. The goal of this chapter is to extend the DataList editing interface to include verification controls. Our verification logic is as follows:

  • The product name is required.
  • Make sure that the entered price value is in valid currency format.
  • Make sure that the input price value is greater than or equal to 0

First, we need to copy the example on the ErrorHandling. aspx page to UIValidation. aspx. This includes the page declaration code and background code. The steps for copying the Declaration Code are as follows:

  1. Open in Visual StudioErrorHandling.aspx
  2. Switch to source view
  3. Copy From<asp:Content>To</asp:Content>The code in the tag is shown in Figure 1.

Figure 1: Copy<asp:Content>Internal code

  1. OpenUIValidation.aspx
  2. Switch to source view
  3. Paste the code.

After completing the preceding steps, open ErrorHandling. asxp. cs, copy the DispalyExcetionDetails method, and process the three events (Products_EditCommand, Products_CancelCommand, andProducts_UpdateCommandDo not copy the declared class and using code. Paste the code into the EditDeleteDataList_UIValidation class in ErrorHandling. asxp. cs.

After completing these steps, you can browse the page. The two pages have the same output and function (see figure 2 ).

Figure 2:UIValidation.aspxPageSame as ErrorHandling. aspx

Step 2: Add a verification control for the EditItemTemplate of DataList

When creating an input table, it is important to declare that required fields and user input must be valid values in the correct format. To ensure that user input is valid, ASP. NET provides five built-in verification controls designed to verify input values in a single input control.

  • RequiredFieldValidator-required value
  • CompareValidator-verifies a value based on the value or constant of another control, or ensures that the input value is of a specific type.
  • RangeValidator-ensure that the input value is within a certain range
  • RegularExpressionValidator-verifies a value based on the regular expression (regular expression ).
  • CustomValidator-validate a value based on the user-defined method

 

For more information about these five Controls, see Add a verification control or Validation Controls section in ASP. NET Quickstart Tutorials to the edit and add interfaces.

In this chapter, we need to use RequiredFieldValidator to ensure that you have entered the product name and CompareValidator to ensure that the price value is greater than or equal to 0 and is a legal currency format.

 

Note: These verification controls are already included in ASP. NET 1.x and have been improved in ASP. NET 2.0. The most important 2.1 is the support for client scripts of browsers other than IE, and the second is the verification control group on the same page. For more information about verifying the new features of Controls in section 2.0, see Dissecting the Validation Controls in ASP. NET 2.0.

Now we need to add the verification control to the EditItemTemplate of DataList. You can click Edit Template on the DataList Smart tag or directly write the declaration code. Here we use the first method. Select Edit Template and drag a RequiredFieldValidator to put it behind ProductName TextBox.

Figure 3: Add RequiredFieldValidator

All verification controls only validate a single Web control. Therefore, we need to specify that the newly added RequiredFieldValidator is used to verify ProductName TextBox. This association verifies the control'sControlToValidateProperty is set as a suitable Web control (ProductName here). ThenErrorMessageProperty is set to "You must provide the product's name ",TextProperty is set to "*". If the value of the Text attribute is provided, it is displayed when verification fails. The ErrorMessage attribute is provided to the ValidationSummary control. If the Text value is omitted, the error message is displayed when the input is invalid.

After completing these steps, your page looks similar to Figure 4:

Figure 4: Set RequiredFieldValidatorControlToValidate,ErrorMessage, AndTextProperties

After RequiredFieldValidator is added, add the verification control for the price of the product. Since UnitPrice is optional during editing, we do not need to add RequiredFieldValidator. What we need to do is add a CompareValidator to ensure that when the price is input, its value is in the correct currency format and greater than or equal to 0.

Add a CompareValidator with the ControlToValidate attribute UnitPrice for EditIteTemplate. Set ErrorMessage to "The price must be greater than or equal to zero and cannot include the currency symbol", and Text to "*". To specify the value of UnitPrice must be greater than or equal to 0OperatorProperty is set to GreaterThanEqual,ValueToCompareProperty is set to "0 ",TypeProperty is set to Currency.

After the two verification controls are added, the EditItemTemplate declaration code of DataList should be similar to the following:

ASP. NET
1            2            3            4            5            6            7            8            9            10            11            12            13            14            15            16            17            18            19            20            21            22            23            24            
<EditItemTemplate>            Product name:            <asp:TextBox ID="ProductName" runat="server"            Text='<%# Eval("ProductName") %>'></asp:TextBox>            <asp:RequiredFieldValidator ID="RequiredFieldValidator1"            ControlToValidate="ProductName"            ErrorMessage="You must provide the product's name"            runat="server">*</asp:RequiredFieldValidator>            <br />            Price:            <asp:TextBox ID="UnitPrice" runat="server"            Text='<%# Eval("UnitPrice", "{0:C}") %>'></asp:TextBox>            <asp:CompareValidator ID="CompareValidator1"            ControlToValidate="UnitPrice"            ErrorMessage="The price must be greater than or equal to zero            and cannot include the currency symbol"            Operator="GreaterThanEqual" Type="Currency" ValueToCompare="0"            runat="server">*</asp:CompareValidator><br />            <br />            <asp:Button ID="UpdateProduct" runat="server" CommandName="Update"            Text="Update" />&nbsp;            <asp:Button ID="CancelUpdate" runat="server" CommandName="Cancel"            Text="Cancel" />            </EditItemTemplate>            

Browse the page. If you do not enter a name or an invalid value in the price when editing, a "*" will appear after the textbox. See Figure 5. A value containing a currency symbol, for example, $19.95, is considered legal. The Currency type of CompareValidator allows numeric delimiters (such as periods and commas) and hyphens (+) or hyphens (-), but not Currency characters. UnitPrice in the editing interface is displayed in currency format, which may confuse users.

Figure 5: "*" appears after invalid Textboxes Input

When the verification control works like the above, you need to manually remove the currency symbol during editing, which is unacceptable. In addition, if an invalid input exists during editing, the page will be postback whether it is a point Update or a Cancel button. Ideally, clicking the Cancel button will return the status before DataList editing, regardless of whether the input value is valid. Of course, because the user's browser may not support JavaScript or be disabled, we must ensure that the page data is valid in UpdateCommand event processing before updating the product information.

Remove the currency symbol from UnitPrice TextBox of EditItemTemplate

When CompareValidator is used, the input cannot contain any currency symbol. Otherwise, CompareValidator is considered invalid. However, the UnitPrice TextBox in the editing interface already contains a currency symbol, which means that you must manually remove it before saving it. We have three methods to fix it:

  1. ConfigurationEditItemTemplateEnableUnitPriceThe format of TextBox value is not currency.
  2. Use RegularExpressionValidator instead of CompareValidator to check the currency values in the correct format. The challenge here is that regular expressions are not as straightforward as CompareValidator, so you need to write some code.
  3. Remove all verification controls, and the verification function will depend entirely on the RowUpdating event processing of the server-side GridView.

Here we use the first method. Now UnitPrice is in the currency format because the binding expression of TextBox <% # Eval ("UnitPrice", "{0: c}") %>. Change itEval ("UnitPrice", "{0: n2}") (two decimal digits are allowed ). You can click the Edit DataBindings link of UnitPrice TextBox in EditItemTemplate in DataList or directly modify the Declaration syntax.

After this is done, the price format on the editing page contains two delimiters: comma (,) and period.

Note: When removing the currency format, I found that it is a good practice to put the currency symbol in front of the TextBox as text. It will remind users that they do not need to enter currency symbols any more.

Fix Cancel Button

By default, the verification control generates JavaScript and performs verification on the client. When you click Button, LinkButton, or ImageButton, the verification control will check before the page postback. If the data is invalid, postback does not occur. However, for some buttons, data does not need to be verified. In this case, it is very annoying to cancel postback.

This is the case with Cancel button. Imagine that the user has entered invalid data, such as ignoring the product name, and then deciding that the user does not need to save the product, and then clicks the Cancel button. In this case, the Cancel button triggers the verification control, which reports that the product name is missing and prevents postback. Our users have to enter some text in the Product TextBox and then cancel the editing.

Validation logic (defaultsTrue). Set the Cancel Button'sCausesValidationPropertyFalse.
Fortunately, there are buttons, linkbuttons, and ImageButton.CausesValidationProperty, which indicates whether verification is required when you click the Button (True by default ). Set CausesValidation of Cancel Button to False.

Ensure that the input is valid in UpdateCommand Event Handler.

The client script is generated by the verification control. If the user inputs invalid data and clicks the button with the CausesValidation attribute set to True, the postback is not triggered. However, if a user uses a browser with a low version or disables support for JavaScript, the client verification will not be executed.

When the page is postback, all the verification controls perform verification and then submit the verification reportPage.IsValidProperty. However, the entire process is not interrupted by the value of Page. IsValid. As a developer, we need to ensure that the code continues to run when Page. IsValid is True.

If JavaScript disabled users browse our page, edit the product, enter a "Too expensive" value in the price, and click Update button. The client verification will be skipped, the page continues with postback. The UpdateCommand event processing will be executed, and then an exception will be thrown when attempting to convert the "too expensive" price to Decimal. Although exception handling has been written, we can block illegal input in the first place based on the Page. IsValid value.

Add the following code at the beginning of UpdateCommand:

C #
1            2            
if (!Page.IsValid)            return;            

After this is done, the product will be updated only when the submitted data is valid. Most users' illegal submission will be rejected due to the client script. customers who do not support JavaScript or disable JavaScript in browsers will skip the client check and submit illegal data.

Note: careful readers will remember that when updating data in the GridView, we do not need to explicitly check Page. IsValid. This is because the GridView has helped us complete this part of work, that is, it will continue to be updated only when Page. IsValid is True.

Step 3: Summarizing Data Entry Problems

In addition to the five verification controls mentioned above, ASP. NET also contains ValidationSummary control, which is used to display error messages for verification controls that check for illegal data. The summarized data can be displayed in text or client message boxes. Now, we will add a client message box that contains verification question summary information.

Drag a ValidationSummary in. As we configure it to display the summary information in the form of a message box, its location does not matter. SetShowSummaryProperty is set to False,ShowMessageBoxProperty is set to True. In this way, all verification error messages are displayed in the client message box. See Figure 6.

Figure 6: Summarize the verification error messages in a client message box

Summary

This chapter describes how to use the verification control to ensure that user input is valid before the update starts, so as to reduce exceptions. ASP. NET provides five verification controls to check input of specific controls and report validity. In this chapter, we use RequiredFieldValidator and CompareValidator to ensure that the product name is required and the price is a currency format greater than or equal to 0.

To add verification controls to the DataList editing interface, simply drag them to EditItemTemplate and set several attributes. By default, the verification control automatically generates a client verification script. Of course, server-side verification is also provided during postback, and all results are accumulated in Page. IsValid. When you click Button, LinkButton, or ImageButton, you can set CausesValidation to False to skip client verification. Before executing any code, make sure thatPage.IsValidTrue.

All of the DataList editing tutorials we 've examined so far have had very simple editing interfaces-a TextBox for the product's name and another for the price. the editing interface, however, can contain a mix of different Web controls, such as DropDownLists, Calendars, RadioButtons, CheckBoxes, and so on. in our next tutorial we'll look at building an interface that uses a variety of Web controls.
Currently, the editing tutorials of DataList are just simple interfaces-displaying name and price in TextBox. However, the editing interface can contain various web controls, such as DropDownLists, Calenda, RadioButtons, and CheckBoxes. In the next chapter, we will create an interface containing various web controls.

Happy programming!

 
Related Article

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.