Using the user control in ASP.net

Source: Internet
Author: User
Tags contains include object model opening and closing tags tag name tagname server memory visual studio
Asp.net| Control "Digest" ASP. NET can solve the problem of code reuse which cannot be solved in ASP, and make the error checking in debugging work more convenient. This article through the user Control realization method explanation and a user control routine realization, further verifies the use user control solves the code reuse the feasibility and the validity.

Keyword code reuse, user controls, @Register directives
Asp. NET provides a better code-splitting scenario than the traditional ASP. In a traditional ASP, you will use the server. The code for an ASP file or transaction object component executed by execute is separated, typically separating the code into several files and then using the "include" method. This method will cause a duplicate of the "include" File in memory (a copy is generated every time the file is referenced), thereby increasing the burden on the system and therefore not feasible. Use the server. Execute may be a bit of a change, but you cannot pass an additional query string parameter to an ASP file that is executing. Using components may be the only good practice. In ASP.net, there are two new technologies that can be used, in addition to the use of "include" (which is not recommended) and transaction object components: Code-behind classes and Web user controls.

Using the Code-behind class can effectively separate the client's HTML code from the server-side event-handling code. The separation of these two parts of code is useful for tracking programs when debugging, because there is no need to switch back and forth between the code that implements the user interface and the logical code of the transaction. Also, if the user interface and transaction processing in a project is developed by a different team, then using the Code-behind class will enable the two parts to be debugged independently. Using the Code-behind class separates the user interface code from the transaction logic code, making the code integrated and maintainable easier. The user controls described below deal with code separation from the perspective of code reuse.

1, User Control Introduction

User controls make it easy for programmers to divide and reuse common UI functionality across ASP.net Web applications. As with Web Forms pages, programmers can use any text editor to author user controls or use code-behind classes to develop user controls. In addition, as with Web Forms pages, user controls can be compiled and stored in server memory on the first request, thereby shortening the response time for subsequent requests. Unlike Web Forms pages, however, you cannot request a user control independently, and the user control must be included in a Web Forms page for use.

Compared to server-side Include files (SSI), user controls give programmers greater flexibility by accessing the object model provided by ASP.net. Programmers can program any property declared in a control, not just the functionality provided by other files, as with any other ASP.net server control.

Although you need to select a language when authoring user controls, programmers can include multiple user controls in a Web Forms page authored in multiple languages. For example, you can use Visual Basic.NET to create a user control, import data from an XML file, and then use C # to create another user control that contains an order form and then includes both controls in the same Web Forms page.

In addition, you can cache the output of the control in a Web Forms page that contains a user control, except for a part of the control. This technology is called fragment caching, and proper use of this technology can improve site performance. For example, if a user control contains a asp.net server control that makes a request for a database, but the remainder of the page contains only text and simple code that runs on the server, the programmer can perform fragment caching on the user control to improve the performance of the application.



2. Create a user control

You can create user controls declaratively by using text or an HTML editor. The user control declaration syntax is very similar to the syntax used to create a Web Forms page, and the main difference is that the user control does not include
User controls can be as simple as text files, or they can contain other ASP.net server controls. The following procedure briefly describes a simple login form that can be included on multiple pages of an application.

Exposes properties, event handlers, and any other code to be included in the user control's functionality in a code declaration block. There are two choices when you use the properties of a user control. First, you can define new properties for the user control and manipulate them. Second, you can manipulate the properties of the server control that make up the user control. For example, if you declare a TextBox Web server control in a user control and provide it with an ID of password, you can use password. Text syntax to manipulate its Text property.

"Note" When a user control is included in a Web Forms page, all the properties and methods of any ASP.net server control contained in this user control are promoted to the public properties and methods of this user control.

Step 1: The following code example declares the UserID and password properties of a text box that maps to code in step 1. You can manipulate these properties in any Web Forms page that contains this user control, either declaratively or programmatically.

Public MustInherit Class LoginForm
Inherits System.Web.UI.UserControl
Protected WithEvents User as System.Web.UI.WebControls.TextBox
Protected WithEvents Pass as System.Web.UI.WebControls.TextBox
Protected WithEvents Button1 as System.Web.UI.WebControls.Button
#Region the code generated by the Web Forms Designer

' This call is required by the Web Forms Designer.
<system.diagnostics.debuggerstepthrough () > Private Sub InitializeComponent ()

End Sub

Private Sub Page_Init (ByVal sender as System.Object, ByVal e as System.EventArgs) Handles Mybase.init
' CodeGen: This method call is required by the Web Forms Designer
' Do not modify it using the Code Editor.
InitializeComponent ()
End Sub

#End Region

Private Sub Page_Load (ByVal sender as System.Object, ByVal e as System.EventArgs) Handles MyBase.Load
' The user code to place the initialization page here
End Sub
Public Property UserId () as [String]
Get
Return User.text
End Get
Set (ByVal Value as [String])
User.text = Value
End Set
End Property
Public Property Password () as [String]
Get
Return Pass.text
End Get
Set (ByVal Value as [String])
Pass.text = Value
End Set
End Property
End Class
Step 2: Create the UI elements that the user control displays. The following code creates a login form that interacts with code from step 1.

Note When you include this user control in a Web Forms page, you need to include this file name and the path to the file in the SRC attribute of the @register directive.

<%@ control Language= "VB" autoeventwireup= "false" codebehind= "Logonform.ascx.vb" inherits= "Logintest". LogonForm "targetschema=" http://schemas.microsoft.com/intellisense/ie5 "%>
<table cellspacing= "15" >
<TR>
<TD> <B> user name: </B> </TD>
<TD> <asp:textbox id= "User" runat= "server" > </ASP:TextBox> </TD>
</TR>
<TR>
<TD> <B> user password: </B> </TD>
<TD> <asp:textbox id= "pass" runat= "server" textmode= "Password" > </ASP:TextBox> </TD>
</TR>
<TR>
<TD> </TD>
<TD> <asp:button id= "Button1" runat= "server" text= "login" borderstyle= "Groove" > </ASP:Button> </TD>
</TR>
</TABLE>

3. Call the user control

A user control can work only if it is included in a Web Forms page. When a request arrives at a page and the page contains a user control, the user control undergoes all the processing stages that are experienced by any server control.

The method of including a user control in a WEB forms page is simple.

In the WEB forms page where you want to include the user control, declare a @register directive that includes:

TagPrefix property, which associates a prefix with a user control. The prefix is included in the start tag of the user control element.

TagName property, which associates the name with the user control. This name will be included in the start tag of the user control element.

src property, which defines the virtual path of the user control file to be included in the Web Forms page.

For example, the following code registers the user control defined in the file Loginform.ascx. The control is also specified with the tag prefix Acme and the tag name login.

<%@ Register tagprefix= "Acme" tagname= "LoginForm" src= "\loginform.ascx"%>

Use custom server control syntax to declare the user control element between the opening and closing tags of the HtmlForm server control (<form runat=server> </form>). For example, to declare a control that was imported in the previous step, use the following syntax.

<%@ Page language= "vb" autoeventwireup= "false" codebehind= "Logintest.aspx.vb" inherits= "Logintest". WebForm1 "%>
<%@ Register tagprefix= "Acme" tagname= "LoginForm" src= "\loginform.ascx"%>
! DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 transitional//en"
<HTML>
<HEAD>
<title> WebForm1 </title>
<meta name= "generator" content= "Microsoft Visual Studio. NET 7.0"
<meta name= "Code_language" content= "Visual Basic 7.0"
<meta name= "vs_defaultClientScript" content= "JavaScript"
<meta name= "vs_targetschema" content= "http://schemas.microsoft.com/intellisense/ie5"
</HEAD>
<body ms_positioning= "GridLayout"
<form id= "Form1" method= "POST" runat= "Server"
<acme:loginform id= "LoginForm" runat= "Server"/>
</form> </BODY>
</HTML>
Note Regardless of how many ASP.net server controls (user controls and any other controls) are included on a Web Forms page, you should include only one HtmlForm server control on a Web Forms page. All server controls should be included between the opening and closing tags of this control.

Using the above program, a user control named Loginform.ascx is called in the Logintest.aspx page, as shown in the following illustration:


4. Summary of User control usage

(1) User controls enable developers to easily define custom controls using the same programming techniques that are used to write Web Forms pages. As a convention, the. ascx file name extension indicates such a control. This ensures that the user control files cannot be executed as stand-alone Web Forms pages.

(2) The user control is included in another Web Forms page through a register directive that specifies TagPrefix, tagname, and SRC location.

(3) After registering the user control, you can place the user control markup in a Web Forms page, including the runat= "Server" property, as normal server controls do. Promote the public fields, properties, and methods of the user control to the public properties (tag properties) and methods of the control in the containing Web Forms page.

(4) The user control participates in the entire execution lifetime of each request, and can handle its own events, encapsulating some page logic from the containing Web Forms page.

(5) The user control should not contain any form controls, but should rely on its containing Web Forms pages to include form controls if necessary.

(6) You can use the LoadControl method of the System.WEB.UI.Page class to programmatically create a user control. The type of the user control is determined by the ASP.net runtime, following the contract file name _ extension.

(7) The strong type of the user control can be used by the containing Web Forms page, even if there is no actual declared user control tag, only if the Register directive is included for the user control.

5. Concluding remarks

When writing a Web application, you can reduce the cost of maintaining your code by using user controls to implement the elements that may be recurring. And when you modify the code, remember to modify a piece of code and forget to modify another piece of the same code will not exist. The shorter the code, the fewer factors that cause the error, the less likely the error will occur.


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.