In the previous article, we discussed how to use it.
The code binding technique in the ASP.NET is to make the code reuse simple and feasible. We have found that using code binding technology we can easily leave our code and content, using it can build reusable code, but this technology itself has some limitations. In this article, we will discuss another new ASP.NET technology: user control.
What is user controls?
In order to better understand the importance of user controls, let's take a look at a small "history". Among the previous ASPs, reusable techniques achieve selection is quite limited. Many developers are generally reused by placing a commonly used child process to achieve a certain so-called code reuse. For example, as we want in a lot of ASP pages in a realistic drop-down list box, I will establish a function in an inclusion file, as follows:
Function getListBox (AssradedItem)
'Build strings for HTML selection controls
'Return this string
END FUNCTION
Of course, such practices are indeed reused to some extent, but in order to make more versatility, you have to add more parameters. In order to make the code you need to organize normal work is difficult, because it is necessary to provide its versatility (reusability), you probably modify these already existing code, so that they can also be in new Normal work under the environment.
VBScript5.0 in IIS5 adds the function of establishing a class. This allows us to achieve reusable code through a more object-oriented way.
Class ComboBox
Property Let ControlName (VDATA)
.
End Property
Ies and methods here>
END CLASS
This will be slightly better, but developers still need to be forced to write those functions to return to HTML code. Moreover, he has no ability to manipulate the events of the instance objects of those classes. In order to make operational events, developers have to build some COM components, while the latter increases the additional complexity of the application.
With ASP.NET, we have a new simple tool to write reusable code-user controls. User control (also called Pagelets) provides a mechanism that allows us to build code components that can be easily used by ASP.NET pages or reuse. A user control is also a simple ASP.NET page, but it can be included in another ASP.NET page. One of the main advantages of using user controls in your ASP.NET application is that the user control supports a full-scale object mode, making you have the ability to capture events. Moreover, user control supports you to write part of the ASP.NET page in a language, and use another language to write another part of the ASP.NET page, because each user control can use the language different from the main page. write.
Create a user control
Before building your own user control, you may want to know which visible objects in your web page is a good candidate that can be reused. It is possible that you will need to use the fused user control on more than one page on your site. Once you start thinking about the structure of your control, you have already prepared it. In our example, we will have a simple search control to search for database Northwind in SQL Server2000. Our search control allows developers to increase search capabilities for a web page.
The first step in establishing the user control is to create a .ascx file. This is the file extension required by the user control. In one .ascx file, you cannot include Head, Form, or Body tag because this label is included in the .aspx file containing this .ascx file. A .ascx file can only contain methods, functions, and in the same way. After establishing a .ascx file, we want to add some visual code for the user control. You can include all web controls in one user control. In our example, search controls need to have a label, a text box, and a button. We first join these web controls because our entire code will involve these objects. Here is the specific code:
There is a cool thing in the user control is that you can define your own properties. In our example, we will define the following properties:
. LabelText-Description Displayed Search Conditions
. ConnectionGString --- Connection string used to join the database
. ResultSetView- contains data records for search results
. TABLENAME - To search the database table name
. Condition - Name of the column of Table you need to search
In order to establish these properties, we use some united GET and SET methods to combine with properties. Before doing these work, we need to first determine if a property needs to be allowed to read, write, or both. For properties that only need to read, we will use the readonly keyword to qualify the statement of the property and only contain the GET method. Our ResultSetView property is a read-only attribute, so its related code looks like this:
'This is a read-only attribute
Public Readonly Property ResultSetView As DataView
Get
'Settings Return Property Values
ResultSetView = dsdata.tables ("boxtitles"). DefaultView
END GET
End Property
For properties that only need to be written, we will use the WriteonLy keyword to qualify the statement of the property and only contain the set method. Our TableName property is a write property, so its related code looks like this:
'This Write Only Attribute Identifies Which Table Will Be Searched
Public Writeonly Property TableName As String
Set
'Setting the name of the table
Strtables = Value
End set
End Property
For those properties that can be read, they do not need to be limited when defined; and also contain GET and SET methods. Once this property is established, the .aspx file can read or set these properties so that the user control can accommodate one or more purposes.
In the user control, the combination of different properties is defined, you also need to define any way, which can be initialized by the user control. These properties and methods define the functionality of the user control. Used in our example is the search method. This method reads the control properties defined in the .aspx file and returns a search result record set. All operating databases are in this method: establish a SQL statement, turn on the database, and return a result from the database.
'This program manipulates a database according to the value of the property.
Public Sub Search (Sender AS Object, e as system.eventargs)
DIM CNCONNECTION As SqlConnection
DIM CMDCommand as SqldatasetCommand
Dim strsserchstring as string
DIM STRSQL AS STRING
'If the user entered the condition in the search box
IF txtsearch.text <> "" "
'Filter out the front and rear spaces of characters
StrsearchString = TRIM $ (txtsearch.text)
END IF
'Establish our SQL statement
strsql = "SELECT *" & _
"From" & strtablename & _
"WHERE" & strconditionfield & "limited '" & _
Trsearchstring & "% '"
'If the coupling attribute is set
IF strConnection <> "" ""
'Establishing a database connection
CNCONNECTION = New SqlConnection (STRCONNECTION)
'Open the database connection
cnconnection.open ()
'Create a new Command object for your search
cmdcommand = new SqldatasetCommand (strsql, cnconnection)
'Create a new DataSet object
DSDATA = New Dataset ()
'Pack DataSet object
cmdcommand.FillDataSet (DSData, "BookTitles")
END IF
End Sub
Once you have added properties and methods in your user control, the development of controls is roughly completed.
Now we have a knowledge of how you have established a user control, let's take a look at how the user control works. Below is what our user control is contained in a form looks like:
Our user controls will be placed on a search page of an international food website. In order to establish this search page, we build an empty .aspx file first. We arrange all the pictures and layouts first, then join our user control.
In order to be able to use this new user control in one .aspx page, you must first initiate the @register directive. When using this tag, you must define the label prefix, tag name, and the source file where you specify the user control.
<% @ Register tagprefix = "jav" tagname = "search" src = "searchControl.ascx"%>
TagPRefix defines the namespace we want to use when we use this user control. Tagname defines the actual name of this user control. You can name your control any, this name will be labeled the user control above the page.
When you join a user control to a .aspx page, the corresponding syntax is similar to the addition of a web control. You first use the label 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, as well as setting the individual defined properties that we have established when we have established the control. There are two ways to modify the properties of these user controls (just like a for one
ASP.NET's web controls). One way is to explicitly set the value of each attribute when referenced by this user control in your web page. In our example, we set the labelText property as "Product Name" because our search is for the product name.
Another method is to set the properties of these user controls in a .ASPX file Page_Load event. For our example, we set up, TABLENAME, and ConditionField properties 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
'Setting up an app for appsettings nodes in config.Web files
HTConfig = context.getconfig ("AP
Psettings ")
'Set the connection string of user controls
UserControl.Connectionstring = (HTCONFIG ("MyConn")))
'Set the name of the table we want to search
UserControl.TableName = "Product"
'Set the name of the field we want to search
UserControl.conditionfield = "Productname"
For our web site, we store the connection string of the database in the area called AppSettings in the config.Web file. (If you want to use the following code, modify Server to your actual server name)
Below is our .aspx file looks like the first time:
Now we need to join the code to call the Search method in our user control. The purpose of our preparation of this user control is to achieve simple search for the database and return search results. To do this, we have two options, we either put our results in our results control (here, usually a DataGrid control), or we will use an ADO record set as a The property returns to the developer, not to care about what the developer uses to display him. Our choice is to return a recordset result via a property, because doing so can make developers can choose what controls for use and what kind of data display mode is adopted.
However, this choice also brings us some questions. We can easily return the results as an attribute to return and use the DataSource property to bind to a DataGrid control or other control. However, how can we know if the user clicks a search button? In order to solve this problem, we need to use page.ispostback in page_load events. If a page is overloaded due to POST, the value of the attribute page.ispostback is equal to TRUE. By detecting whether the page.ispostback is equal to TRUE, we can decide whether to call the Search method in our user control, then bind the result to our DataGrid.
'Test the value of the page.ispostback property
IF page.ispostback = True Then
'Executive action
UserControl.Search (Objsource, Objargs)
'Bind the results to the DataGrid control
Grdgrid.DataSource = UserControl.ResultSetView
'Officially binding data
grdgrid.database ()
END IF
End Sub
After an individual enters a search criteria and submits the display page after our .aspx file:
Now we can build another page for use in our site. We will perform a search action in this second page to be built, but this time you have to search on the COMPANYNAME field on the Northwind database table Company. In order to establish this page, we build 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. We will set different values in this page. The coupling string still retains the same value in front. We need to set the value of the property LabelText equal to Company Name, setting the value of the property Table is equal to Company, setting the value of the attribute ConditionField is equal to CompanyName. Through the slight change of layout and user controls, we have completed this page. For this page, we only need little code, which is good to thank the code to reuse the user controls. Here is our new page:
As you can see, the user control can provide a simple method to implement the reusability of the code, and save a lot of unnecessary trouble. Moving the associated controls and code from an ASPX file to an ASCX file is an appropriate approach, and only a smaller modification can make the code work normally.
limitation?
You may ask yourself: What do I use to use user controls? There are few restrictions on using this technique.
One of them is that the user control does not support the template. Therefore, you cannot establish a user control to achieve the functionality of the Data Repeater control provided in the ASP.NET.
Another limit is: Since the user control must contain some static UI (user interface) attributes, you can't adjust them in strict adjustment according to your ideas. For example, you may want to build a user control containing multiple controls, and allow developers to specify the display order of these controls on the page. The above idea is difficult for a user control because the UI block is static setting.
in conclusion
User controls provide an excellent way to make it very easy to reuse the code in your ASP.NET page. Drag and drop some code in ASP.NET to the ASCX files make them reuse them to be correct selections and practices.
In our article, we explore the reuse of the code in ASP.NET together by customized control. Customizable ASP.NET controls can provide additional elasticity for reusable code, as we have learned above.