Practical ASP. NET skills

Source: Internet
Author: User

This article mainly introduces some common methods in ASP. NET programming, including code skills and performance optimization.

1. execution on the tracking page
Setting breakpoints is a common method in page debugging. In addition, you can view the tracing information of the page for error troubleshooting and performance optimization. It is very convenient to enable Page tracing in ASP. NET. You only need to add the Trace = "True" attribute to the Page command:

<% @ Page Language = "C #" Trace = "true">

There are two types of tracking information:
A. Page execution details
It mainly includes the list of events in the page lifecycle and the Control tree list (you can view the number of HTML bytes for each control and the number of ViewState bytes) session Status, Application status, Cookie set, QueryString set, server variables, and other information.
B. Custom tracking information
By calling the Trace. Write () or Trace. Warn () method in the page code, you can Write the specified content to the "Trace Information" section in the Trace Information. Even if an error occurs on the Page, the Trace information is displayed, and the tracing Code does not need to be deleted when the application is released. You only need to remove the Trace attribute from the Page command.


2. Add client properties to the server control
We sometimes add some special attributes to the server-side controls. This type of attribute does not need to be processed by the server, but simply needs to be sent to the client. We may consider it as the client property, for example, HTML or custom attributes (which may be used to implement certain JavaScript Functions ). You can achieve this through the following methods:
A. directly add client properties to the control

<Asp: Button ID = "MyButton" Text = "ClickMe" onmouseover = "this. style. cursor = 'pointer '" runat = "server"/>

Onmouseover is a client attribute. Note that the compiler allows this write method, but a warning is displayed.
B. Call the built-in method
You can call WebControl. Attributes. Add () to Add client properties for the control, as shown below:

MyButton. Attributes. Add ("onmouseover", "this. style. cursor = 'pointer '");

This is also the most common method.
C. Create a custom control
If you need to add client properties to a type of server-side control, you can create a custom control that inherits from the server-side control, which contains specific client properties.
With this in mind, ASP. NET 2.0 provides the OnClientClick attribute for the Button control (including the Button, LinkButton, and ImageButton controls), which can be written as follows:

MyButton. OnClientClick = "alert ('Hello! ')";

This is a caring feature!

3. server-side verification of form data
The process of migrating data verification tasks from the server to the client promotes the generation of JavaScript, which is also a method we have used so far. However, this method can only be used to ensure the normal operation of the client JavaScript. Unfortunately, there are always some exceptions, such as the browser does not support JavaScript, or the user deliberately closes the JavaScript function of the browser, which leads to the first protection failure. It is safer to add the second protection, that is, to verify the data submitted by the user on the server, but this will undoubtedly increase the workload of developers.
ASP. NET 2.0 provides a series of form data verification controls to easily complete dual data verification tasks on the client and server. However, the Page. IsValid attribute must be used for server-side verification. See the following example:

<Form id = "MyForm" runat = "server">
<Div>
Name: <asp: TextBox ID = "txtName" runat = "server"> </asp: TextBox> & nbsp; <asp: requiredFieldValidator ID = "RequiredFieldValidator1" ControlToValidate = "txtName" ErrorMessage = "Please enter your name! "Display =" Dynamic "runat =" server "> </asp: RequiredFieldValidator>
</Div>
<Div>
<Asp: Button ID = "btnSubmit" Text = "Submit" runat = "server"/>
</Div>
</Form>

This is an HTML clip, with a RequiredFieldValidator control used to check whether a name is filled in. The following is the server code executed when you click the button:

Protected void btnSubmit_Click (object sender, EventArgs e)
{
This. style. display = 'none'; document. getElementById ('codehighlighter1 _ 59_173_Open_Text '). style. display = 'none'; document. getElementById ('codehighlighter1 _ 59_173_Closed_Image '). style. display = 'inline'; document. getElementById ('codehighlighter1 _ 59_173_Closed_Text '). style. display = 'inline ';
} "Alt =" "src =" http://kb.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif "align =" top "> {
This. style. display = 'none'; document. getElementById ('codehighlighter1 _ 59_173_Closed_Text '). style. display = 'none'; document. getElementById ('codehighlighter1 _ 59_173_Open_Image '). style. display = 'inline'; document. getElementById ('codehighlighter1 _ 59_173_Open_Text '). style. display = 'inline ';
} "Alt =" "src =" http://kb.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif "align =" top "> {
If (Page. IsValid) // Note: Do not omit the judgment on the Page. IsValid attribute.
{
This. style. display = 'none'; document. getElementById ('codehighlighter1 _ 115_171_Open_Text '). style. display = 'none'; document. getElementById ('codehighlighter1 _ 115_171_Closed_Image '). style. display = 'inline'; document. getElementById ('codehighlighter1 _ 115_171_Closed_Text '). style. display = 'inline ';
} "Alt =" "src =" http://kb.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif "align =" top "> {
This. style. display = 'none'; document. getElementById ('codehighlighter1 _ 115_171_Closed_Text '). style. display = 'none'; document. getElementById ('codehighlighter1 _ 115_171_Open_Image '). style. display = 'inline'; document. getElementById ('codehighlighter1 _ 115_171_Open_Text '). style. display = 'inline ';
} "Alt =" "src =" http://kb.cnblogs.com/Images/OutliningIndicators/ContractedSubBlock.gif "align =" top "> {
Response. Write ("Your name is:" + txtName. Text );
}
}

Pay special attention to Page. isValid attribute judgment, Page. the IsValid attribute is True, which indicates that the submitted data is valid and you can proceed to the next step.

4. Skip Form Verification
In some cases, we need to skip the verification of all controls in the form. However, in other cases, we want to have the verification function of some controls in the selected trigger form. Let's take a look at these two situations:
A. Skip all verification
Assume there is a form. In addition to various data entry controls, there are two buttons, one is the submit button, the other is the cancel button, and the form also contains some data verification controls. You do not need to verify the validity of the data in the form when you click the cancel button. Instead, you can directly submit the page to the server and redirect it to a specified page.
To implement this function, you can use the CausesValidation attribute of the Button control (including the Button, LinkButton, and ImageButton controls) to set this attribute to false to skip all verification in the form.
B. Trigger some verification
Assume that a form is divided into two functional areas: one for user login and the other for user registration. We hope that only data verification in the logon zone will be triggered when the login button is clicked, when you click the register button, only data verification in the registration area is triggered.
The solution is to add the related data verification controls and data submission controls (button controls) to the same verification group, this is achieved by setting the ValidationGroup attribute of each related control to the same value.

5. Keep the scroll bar position
Assume that there is a page where some data records are displayed in the form of a list. Each time you edit the records, you must submit the page to the server. In order to provide a good user experience, we hope that the position of the scroll bar will remain unchanged after a record is edited and saved. The traditional method is to send the information of the current scroll bar location (Hidden field or QueryString) to the server every time a page is submitted. When the page returns to the client, the server resets the scroll bar position in JavaScript format based on the input location information.
If you use ASP. NET to implement this function, you only need to add the MaintainScrollPositionOnPostback = "true" attribute to the Page command:

<% @ Page Language = "C #" MaintainScrollPositionOnPostback = "true">

 
6. disable unnecessary ViewState

ViewState plays an important role in the ASP. NET operating mechanism. After ViewState is encoded, it is saved to the form Hidden field and decoded whenever the page is returned to the server. Therefore, ViewState may cause two problems: bandwidth usage and computing resource consumption. Fortunately, not all controls need to enable ViewState. we can disable unnecessary ViewState.
ViewState is enabled by default and needs to be disabled manually:
A. Disable page ViewState
Add the EnableViewState = "false" attribute to the Page command:

<% @ Page Language = "C #" EnableViewState = "false">

After this attribute is added, ViewState cannot be used for the entire page and all controls in it, so you need to use it with caution.
B. Disable the ViewState control.
This is a recommended method. Set the EnableViewState attribute of the control to False to disable its ViewState. Here is a simple trick:
If the status of a widget cannot be changed by the operator, you can disable its ViewState. The most typical is the Label control, which only displays information and cannot be operated.
However, the status of TextBox, DorpDownList, and other controls can be changed (through input, selection, and other operations), so retaining their ViewState is still useful.

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.