ASP. NET User Control Technology

Source: Internet
Author: User

We found that using code binding technology we can easily separate our code and content and use it to build reusable code, but this technology also has some limitations. In this article, we will discuss another new ASP. NET Technology: user control.
  
What is User Controls )?
To better understand the importance of user controls, let's take a look at a small "history ". In the past ASP, reusable technical implementation choices were quite limited. Many developers generally put common sub-processes into those containing files to achieve code reuse. For example, if we want to create a drop-down list box in many ASP pages, I will create a function in an included file, as shown below:
  
Function GetListBox (asSelectedItem)
'Create a string for the HTML Selection Control
'Return this string
End Function
  
Of course, this practice is indeed reused to a certain extent, but in order to be more universal, you have to add more parameters. It is difficult to make the code you need to organize work like above work properly, because to provide its versatility (reusability), you probably have to modify the existing code, so that they can work normally in the new environment.
VBScript5.0 in IIS5 adds the function of creating classes. This allows us to implement reusable code in a more object-oriented way.
  
Class ComboBox
Property Let ControlName (vData)
.
End Property
  
End Class
  
This is slightly better, but developers still need to be forced to write those functions to return HTML code. In addition, he is not able to manipulate the events of those class instance objects. In order to perform Operation events, developers have to create some COM components, while the latter increases the extra complexity of the application.
  
With ASP. NET, we have a new simple tool to write reusable code-user controls. User Controls (also called pagelets) provide such a mechanism that allows us to build code components that can be easily used or reused by ASP. NET pages. A user control is also a simple ASP. NET page, but it can be included by another ASP. NET page. One of the main advantages of using user controls in your ASP. NET applications is that user controls support a fully object-oriented mode, allowing you to capture events. In addition, user controls allow you to write ASP in one language. NET page, and use another language to write ASP. NET page, because each user control can be written in a different language than the home page.
  
  
Create a user control
Before creating your own user control, you may want to know which visible objects on your web page are good candidates for reuse. It is possible that you will need to use integrated user controls on more than one page on your site. Once you start to think about the structure of your control, you are ready to start. In our example, we will create a simple search control to search for the database Northwind in SQL Server2000. Our search control allows developers to quickly add search capabilities to a web page.
  
The first step to create a user control is to create a. ascx file. This is the file extension required by the user control. A. ascx file cannot contain head, form, or body labels, because the. aspx file containing this. ascx file already contains these labels. A. ascx file can only contain methods, functions, and user controls.
  
After creating a. ascx file, we want to add some visible code to the user control. A user control can contain all web controls. In our example, the search control requires a tag, a text box, and a button. We first add these web controls, because these objects are involved in our entire code. The specific code is as follows:
  
    
    
  
  
One cool thing in user controls is that you can define your own attributes. In our example, we will define the following attributes:
  
. LabelText-Description of the search criteria displayed to the user
. ConnectiongString --- the connection string used to connect to the database
. ResultSetView-data record set containing the search results
. TableName-name of the database table to be searched
. Condition-name of the column of the table to be searched
  
To create these attributes, we use the get and set methods combined to combine them with the attributes. Before doing this, we need to determine whether a property needs to be read, written, or both. For attributes that only need to be read, we will use the ReadOnly keyword to limit the attribute declaration and only include the get method. Our ResultSetView attribute is a read-only attribute, so its related code looks as follows:
'This is a read-only attribute.
  
Public ReadOnly Property ResultSetView as dataView
Get
'Set the returned property Location Value
ResultSetView = dsData. tables ("BookTitles"). defaultview
End Get
End Property
  
For attributes that only need to be written, we will use the WriteOnly keyword to limit the attribute declaration and only include the set method. Our TableName attribute is a write-only attribute, so its related code looks as follows:
  
'This write only attribute identifies which table will be searched
Public WriteOnly Property TableName as string
Set
'Set the table name
StrTableName = Value
End Set
End Property
  
For those attributes that can be read or written, you do not need to limit them when defining them. The Get and Set methods are also included. Once this attribute is created, the. aspx file can read or set these attributes so that the user control can be used for one or more purposes.
  
In a user control, you need to define any methods in combination with different attributes. These methods can be initialized by the user control. These attributes and Methods define the functions of user controls. The search method is used in our example. This method reads the control attributes defined by each user in the. aspx file and returns a search result record set. All the code for manipulating the database is in this method: Create an SQL statement, open the database connection, and return a result from the database.
  
'The program operates a database based on the attribute value.
Public Sub Search (sender As Object, e As System. EventArgs)
Dim cnConnection As SQLConnection
Dim Metadata Command As SQLDataSetCommand
Dim strSearchString As String
Dim strSQL As String
'If the user enters a condition in the search box
If txtSearch. Text <> "" Then
'Filter out spaces before and after characters
StrSearchString = trim $ (txtSearch. Text)
End If
'Create our SQL statement
StrSQL = "Select *"&_
"FROM" & strTableName &_
"Where" & strConditionField & "LIKE '"&_
TrSearchString & "% '"
'If the connection property is set
If strConnection <> "" Then
'Create a database connection
CnConnection = New SQLConnection (strConnection)
'Open the database connection
CnConnection. open ()
'Create a new command object for the search
Custom command = New SQLDataSetCommand (strSQL, cnConnection)
'Create a new DataSet object
DsData = New DataSet ()
'Fill the dataset object
Using command. FillDataSet (dsData, "BookTitles ")
End If
End Sub
  
Once you add properties and methods to your user control, the development of the control is roughly complete.
Now we have an understanding of how a user control is created. Let's see how the user control works. The following figure shows what our user control looks like when it is included in a form:
  
Our user controls will be placed on a search page on an international food website. To create this search page, we first create an empty. aspx file. We first arrange all the images and la s, and then add our user controls.
To use this new user control on a. aspx page, you must first initialize the @ Register command. When using this tag, you must define the tag prefix, tag name, and the source file of the specified user control.
  
  
  
TagPrefix defines the namespace we want to use when using this user control. TagName defines the actual name of the user control. You can name your control at will. This name will be used to mark the user control on the page.
When you add a user control to A. aspx page, the corresponding syntax is similar to adding a web control. You first use the tag prefix and Tag name to mark the user control:

Now we have this space on the page. We can set the standard runat and id attributes, and set the attributes defined by ourselves when we previously created the control. There are two ways to modify the attributes of these user controls (just like for an ASP. NET web control ). One way is to explicitly set the values of each property when you reference this user control on your web page. In our example, we set the LabelText attribute to "Product Name" because our search is for the Product Name.
  
  
  
Another method is to set the attributes of these user controls in the page_load event of A. aspx file. For our example, we set the ConnectionString, TableName, and ConditionField attributes in the page_load event. We need to search for the ProductName field of the Product table in the database Northwind.
  
Sub page_load (objSource as Object, objArgs as eventArgs)
Dim htConfig As HashTable
'Set an application for the ettings node in the Config. web file
HtConfig = Context. GetConfig ("appsettings ")
  
'Set the connection string of the User Control
UserControl. ConnectionString = (htConfig ("MyConn "))
  
'Set the name of the table to be searched.
UserControl. TableName = "Product"
  
'Set the name of the field to be searched.
UserControl. ConditionField = "ProductName"
For our web site, we store the database connection string in the region called deleettings In the Config. web file. (If you want to use the following code, change the server name to your actual server name)
  
  
  
  
The following is what our. aspx file looks like for the first time:
  
  
  
Now we need to add code to call the search method in our user control. The purpose of writing this user control example is to implement simple search for the database and return the search results. To achieve this, we have two options: Put our results in our results control (here, it is generally a DataGrid Control) in our user control ), you can either return an ADO record set as an attribute to the developer without worrying about how the developer uses it to display it. Our choice is to return a record set result through an attribute, because this allows developers to freely choose what controls to use and what data display methods to use.
However, this choice also brings us some problems. We can easily return the result as a property and bind it to a DataGrid control or other controls using the DataSource property. But how can we know whether a user clicks a search button? To solve this problem, we need to use the Page. IsPostBack attribute in the page_load event. If a Page is reloaded due to post, the value of Page. Ispostback is equal to true. By checking whether page. ispostback is equal to true, we can decide whether to call the Search method in our user control and then bind the result to our datagrid.
  
'Check the value of the Page. IsPostBack attribute
If page. IsPostback = true then
'Action to perform the search
UserControl. Search (objSource, objArgs)
'Bind the result to the DataGrid Control.
GrdGrid. datasource = userControl. ResultSetView
'Formally bind data
GrdGrid. databind ()
End If
End Sub
After a person enters a search condition and submits our. aspx file, the following page is displayed:
  
  
  
Now we can create another page to use on our site. The second page we will create will also perform a search action, but this time we will perform a search match on the CompanyName field in the Company table of the Northwind database. To create this page, we create a new blank. aspx file. Since this page is similar to our product page, we use the same layout. We will use the search user control again.
  
  
  
On this page, we will set different values for attributes. The same value is reserved for the join string. We need to set the LabelText value to "Company Name", set the Attribute Table value to "Company", and set the attribute ConditionField value to "CompanyName. By slightly modifying the layout and user controls, we have roughly completed this page. For this page, we only need a small amount of code. Thanks for the code reuse brought by the user control. The following is our new page:
  
  
  
As you can see, user controls can provide a simple way to achieve code reusability, saving a lot of unnecessary trouble. Moving related controls and code from An ASPX file to an ASCX file is an appropriate practice. You only need a small modification to make the code work normally.
  
Limitations?
You may ask yourself: What can't I do with user controls? There are few restrictions on using this technology.
One restriction is that user controls do not support templates. Therefore, you cannot create a user control to implement the Data Repeater control function provided in ASP. NET.
Another restriction is that user controls must contain some static UI (User Interface) attributes, so you cannot strictly adjust them according to your ideas. For example, you may want to create a user control that contains multiple controls and allow developers to specify the display sequence of these controls on the page. The above idea is difficult for a user control, because the UI block is set statically.
  
Conclusion
The user control provides an excellent way for you to easily reuse code on your ASP. NET page. Drag and Drop some code in ASP. NET into the ASCX file so that they can be reused is a correct choice and practice.
In our article, we discussed how to reuse code in ASP. NET through custom controls. Custom ASP. NET controls provide additional flexibility for reusable code, as we have learned above.

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.