ASP.NET Reuse Code Technology - User Control Technology

xiaoxiao2021-03-06  119

Author: Suhongtu Ultra

Use code binding techniques in ASP.NET to make the code reuse simple 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, if we want to realize a drop-down list box in many ASP pages, I will build a function in an inclusion file, as shown below: Function getListBox (ass "is built for HTML selection control build strings' Back This string end function is of course, this practice is 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

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. Below is the specific code: < asp: button id = cmdsearch runat = "server" text = "search"> 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-Describe the search criteria displayed to the user. ConnectionGString --- The connection string used to join the database. ResultSetView- contains data records for search results. TableName - To search the database table name. Condition-The name of the list of Table needs to be searched 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 property, so it's related code looks like this: 'This is a read-only property public Readonly Property ResultSetView AS DataView Get' Settings Return Properties ResultSetView = DSData.Tables ("BookTitles" ). DEFAULTVIEW END GET End Property For only the 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-only property, so it's relevant code looks like this: 'This write only attribute identifies which table will be searched Public WriteOnly Property TableName as string Set' to set the table name strTableName = Value End Set End Property for Those properties that can be read can also be written, they don't 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. 'The procedure in accordance with the value of the attribute to manipulate a database Public Sub Search (sender As Object, e As System.EventArgs) Dim cnConnection As SQLConnection Dim cmdCommand As SQLDataSetCommand Dim strSearchString As String Dim strSQL As String' if the user inputs a search box Condition IF TXTSEARCH.TEXT <> "" "" THEN 'Filtering the front and rear space STRSEARCHSTRING = TRIM $ (txtsearch.text) end if' builds our SQL statement strsql = "SELECT *" & _ "from" & strablename & _ " Where "& strconditionfield &" Like '"& _ TRSearchString &"%' "If the coupling attribute is set with if strconnection <>" "build database connection CNCONNECTION = New SQLConnection (STRCONNECTION) 'Open the database connection CNConnection.Open ) 'Creating a new Command object cmdcommand = new sqldatasetCommand (strsql, cnconnection) Creating a new DataSet object DSData = new dataset ()' populates the DataSet object cmdcommand.FillDataSet (DSData, "BookTitles") Endness 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 an form: our user control 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 label name to mark the user control: Now we have this space on the page, we can set the standard Runat and ID properties, and set up our previous control The individual defined properties that are established are created. There are two ways to modify the properties of these user controls (just like a web control for an ASP.NET). 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. The other 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 'is provided on an application htConfig Config.web file AppSettings node = Context.GetConfig ( "appsettings")' set the connection string userControl.ConnectionString user control = (HTCONFIG ("MyConn") "Sets the name of the table we want to search for userControl.Tablename =" product "Set the field name we want to search UserControl.conditionfield =" ProductName "For our Web site, we connect the database connection The string is placed 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) < / appSettings> The following is our .aspx file for the first time looks like: 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. Operation userControl.Search (objSource, objArgs) 'If page.IsPostback detected value Page.IsPostBack attribute = true then' perform a search 'will be bound to the results above DataGrid control grdGrid.datasource = userControl.ResultSetView' formal binding data grdGrid .DATABIND () end if End Sub Enter a search criteria after entering our .ASPX files: 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 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. Limitations? You may ask yourself: What can I do with 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.

转载请注明原文地址:https://www.9cbs.com/read-100106.html

New Post(0)