Easily develop perfect web form controls using .NET framework

xiaoxiao2021-03-06  89

Release Date: 8/6/2004

| Update Date: 8/6/2004

David S. Platt

This article assumes that you are familiar with Visual Basic .NET, C # and HTML

Download this article: Webc.exe (274KB)

Abstract Pre-built custom controls can simplify and speed up the design of the application and enable you to maintain the consistency of the UI. However, the pre-packaged control may be large, the speed is slow, and it is specific to the operating system. For those who are unwilling to use pre-packaged controls, Visual Studio .NET provides web form controls similar to the controls in the Windows Form, including labels and text boxes, and new DataGrid, all of which controls Custom can be made. If you want to design your own control, you can avoid overcomparable work processes by using the inheritable class provided by the .NET framework, including page survival cycles, maintenance status between calls and browser detection. This article will introduce these concepts and event processing, rendering, and client scripts.

The control is a very attractive concept. When using a pre-packaged UI function, you can complete the design faster, cheaper, and you can maintain a more consistent UI between different applications. But this is not all of its features. Controls may also be large, compared to code specifically prepared for specific tasks, can run slower. Also, Windows-based controls such as Windows Form Controls and early ActiveX, OCX, and VBX controls can only be run in a Windows environment - this is very intended to have a new platform type with new platform types. problem.

In order to be able to run across the platform, Microsoft designed the web form structure asp.net. With Visual Studio, you can select components called web form controls from the toolbox and place them on the ASPX page. You can then set the properties of the control and write code using any language of the .NET, thereby associating it with other controls. This process is designed to be similar to using Visual Basic to write applications. This is a very familiar process for most programmers.

Figure 1 request

When the client requests the page containing the web form control, the ASP.NET processor will load this page and create these controls on the server, as shown in Figure 1, and then execute the programming logic of the page, and associate the control together. At the end of this process, each control provides an HTML that describes its current appearance to ASP.NET. These HTML will be returned to the client and rendered in the browser. Read information about ASP.NET Web Forms: ASP .NET: Web Forms Let You Drag and Drop Your Way To Powerful Web Apps.

Visual Studio comes with a set of universal web form controls, or more or less corresponds to the available control groups in the Windows Form. It contains tags and text boxes, and the like, which have been familiar with you, also contains updates, more complex controls such as DataGrid.

This article describes the features provided by the .NET framework for writing your own web form controls. Since I have already introduced the basic concepts (Methods, Attributes and Events) of the controls in MSDN® Magazine, I will mainly describe the difference between web form controls and Windows-based controls. These differences are mainly due to the operation of running in a relatively simple browser runtime environment, rather than running in a rich Windows environment.

.NET support for developing web form controls

The .NET framework contains pre-created software classes that make the WEB form control becomes relatively simple. You need to understand HTML to generate the output required by the control, just like the designer of the Windows Form Control needs to understand Windows GDI. However, the routine that hooks to the ASP.NET page survival cycle, the routine that maintains the status between multiple calls, and the routine that detects the host browser feature (the infrastructure that all controls) has been written for you. You can write controls with the .NET compatible language to use the pre-created infrastructure by inheriting from the several .NET framework class selected. These base classes are generally corresponding to classes in the Windows form. However, common situations are that Microsoft uses the same name to refer to things in a similar environment, so you must be cautious, and read the subsidiary rules. Here is five ways to develop Web form controls.

The first choice is derived from system.web.ui.control, which is the base class of all web form controls. It is involved in all survival cycle events of the ASP.NET page presentation process. The document indicates that this class does not have any user interface, although it exists in the System.Web.ui namespace. I have different opinions. It contains a render method (described in the next section), the control uses this method to issue HTML to be displayed in your browser. It has a relatively built-in UI property than the next class I want to introduce; for example, it does not have Width, Height, Forecolor, Backcolor, and Font, but if you must use it to generate a UI, it is still very easy. It is more lightweight due to omitting the above elements, but there is a minimal difference. If you don't pay attention to any of the features it omit, use it as a base class without problems.

Your next option is derived from System.Web.ui.WebControls.WebControl, which is derived from System.Web.ui.Control. This is a control that adds basic user interface properties. Visual Studio automatically uses it as a base class when you generate a new web control library project. If you want to get a control like most controls, you may start here.

You can also start from the existing web form control, which can be the control attached to Visual Studio, or the control purchased from a third party. At this point, you need to use the .NET inheritance mechanism from existing controls to derive your own controls. You need to reuse the parts you need in your existing feature, override the part you want to change, and add any additional features to enable the control. In my previous article, I have introduced how to use the Windows Form Text Box Control to complete the above tasks. Complete this task is exactly the same for web form controls, which is no longer repeated here.

Another option is to design a control containing other controls. In a Windows Form, it is called a user control, but in a web form, it is called a composite control. You can choose any of the three inheritance schemes described above for your base class. Unfortunately, the web form is not supported by the Windows Form. Therefore, you must manually create and locate child controls in your code. This is not difficult, so this is not discussed. However, I found that this province is very surprising.

Finally, you can choose to create a user control. Each control discussed above is fully compiled .NET assembly. They can be used in the Visual Studio toolbox and designer, and can be saved in the Global Assembly Cache (GAC), so there is no need to use a separate copy for each client to use. The Web Form provides another method (user control) that generates a reusable control package. Like the user control you see in a Windows Form, the web form user control is generated by placing other controls into the design map in the Visual Studio designer. However, different from the Windows Form User Control, this user control is an HTML page, not the compiled assembly, so you cannot save it in the GAC or Visual Studio toolbox, and you cannot display in the Visual Studio designer. Its appearance. So I think it is far less than other types of web form controls I have introduced. I suspect that it exists because of the lack of designer support in the composite web form control. Back to top

Simple custom control

When learning or explaining new software, I will always start from the simplest example I can think of. This is a label control, which contains a property called Text, which is the string displayed by the label, which also contains an attribute called ForeColor, which is the color of the text string (see Figure 2).

Figure 2 Tag control

I first generated the project in Visual Studio and then selected Web Control Library from the New Project dialog, as shown in Figure 3. The wizard generates a project that contains a new class derived from System.Web.ui.WebControls.WebControl. Add methods and properties to this class and attribute to any other .NET class. In fact, the base class provided by the system already contains properties called Text and ForeColor used in this example.

Figure 3 Generating items

Just like I said, this is very simple. Basically, this is basically like this. Understanding the key to custom web form controls is that the render method, which is conceptually the same as the Windows form onpaint method, and the difference is only the former HTML, and the latter issues a GDI call. When the ASP.NET server framework assembles a web form page for response to a user request, it will create the controls listed on the page, set the properties of these controls and persistence data, and then call their respective render methods. The framework is actually telling the control: "You are active and is in the expected state. You need to tell me your look, because I don't have any other way to understand." The author of the web form control will be in the render method In stock to issue HTML to inform the browser how to display the appearance of the control based on any other information in the environment related to the control.

The author of the Web Form Control requires HTML because there are few information provided by the environment. The following is an HTML that specifies a text color:

Here is some text

In order to generate these HTML, I wrote the code shown in Figure 4. Most readers told me that they hope that the source code is written using Visual Basic; in order to take care of C # readers, I use Visual Basic and C # two languages ​​to write downloadable sample code.

When the ASP.NET Framework calls the RENDER method of the control, a system.Web.ui.htmlTextWriter type object is passed. This is conceptually similar to the ONPAINT method to the Graphics member of the System.Windows.Forms.PainTeventargs received in the Windows Form Control. Both represents the connection of the frame, the framework to position it to its corresponding position. HtmlTextWriter contains methods, properties, and constants that allow your control to send HTML to the output page that will be sent to the client browser. In the sample code, I first call the method addStyaAttribute, which creates a value called the style, which is set to the value of the ForeColor property inherited by the control, and then add it to the internal buffer. The added value of the style attribute can be added to the buffer by adding the additional call of the AddStyaAttribute; by calling the AddAttribute method, other properties can be added, of course, in this case, do not need to do it. Next, I call the method renderbegintag, specify the name of the HTML tag to display in the text, this example is "SPAN". This call extracts any attributes from the internal buffer (here STYLE), placing them into the tag, and then writes in the HTML output stream. These two calls generate the first line HTML:

Next, in order to write the tag text, I call the method HTMLTextWriter.Write to deliver the internal text string of the control. This method passes the text string Verbatim into the HTML output stream, resulting in the second line:

Here is some text

In order to close the mark, I called HtmlTextWriter.Renderendtag. This causes the writer to read back the last open tag, and issues the closing mark of the tag, in this example, as the last line HTML. This object contains other methods for performing output, which provide more fine controls, but more complicated. For the sake of simplicity, I will use the front method in the rest of this article.

Figure 5 Add a new control to the toolbox

Finally, I need a client to use the control to debug and display it. I added a new web application that contains an ASP.NET page to an existing solution. In order to add a new web form control to the toolbox, I am right-click and select Customize Toolbox to call the dialog shown in FIG. 5. I browsed the new web control DLL, select it, the control appears in the list of controls, as shown in Figure 6.

Figure 6 New controls in the list of controls

After that, it can be placed on the ASPX page and set its properties. Generate a project and start it in the browser, the appearance of the control is shown in Figure 2.

Back to top

More complex example

Now, we have already introduced the basic features of the .NET web control, let us look at an example, which demonstrates how the web form control is excited to other controls on the page. NET event. I found that the SDK documentation is very vague when introducing Web control events. It uses the user's click (thus startup process) on the browser, and the notification of the servers that it triggers and the notification sent by the retreaded server-side control to the other controls on the page are all defined as an event. Below, I will try to accurately describe the differences between these events.

I have written a more complex sample control that is displayed on the ASPX page in Figure 7. It displays a table in the user's browser that shows your line number and column number in each cell of the table. This control is disclosed as the properties of Rows and Columns. These two attributes are integer, setting up when designing. When the user clicks on any cell in the table, the form will be raised to the server. After assembled and initialized the page, the table control will determine which cell is the user clicked, and the other controls that are willing to listen to the page on the server. Net framework events. In this example, the page contains an event handler that sets the value of a separate tag control to display the line number and column number of the unit clicked. Figure 7 Table Control

When this control is developed, I will first write the render method to the HTML that disables the table with the number of tables and the number of columns, which is very simple. Next, I want to add a browser to return the form back to the server's HTML when the user clicks on the table. This requires some other techniques (see Figure 8).

It can be seen that each table data item () creates a cell and contains an OnClick property that calls a client script that passes the server-side control to handle the return (for the table control in this example). ID and a string containing any parameters. Here, the string is the text of the table cell, which enables the server-side control to identify the cell clicked by the user, but the string can be anything you need. The image is displayed on the bottom of the picture to place these parameters into the hidden input control and perform a return to the server.

Later I will explain the server-side of this return, let's take a look at how these HTMLs are generated. This looks very cumbersome, good news is that you don't need to write them yourself. Keep in mind that your control exists on the ASP.NET page, so you can access all methods of the page through the base Page class member variable. Method Page.GETPostBackeventReference causes the HTML script on the framework to generate the page and returns the HTML string that calls it. Next, I add this string to the properties of the element, which can use the aforementioned HTMLTextWriter method. You can see the code of the Render method in Figure 9. Please ignore the code part of the processing view status; I will explain them in the next section. )

What should I do if the browser can't run JScript? I will explain later. Now, first assume that the browser can run JScript, or we clearly state that we only pay attention to the situation where the browser can run JScript.

The return form reaches the ASP.NET, ASP.NET loads the target page on the server and creates the control it above. ASP.NET needs to pass the return to its target control. ASP.NET is known to the hidden input control filled through the client script. The server-side control is to accept the input notification by implementing an interface called iPostBackeventHandler and overwriting the RaisePostBackevent method. I think this method name is very easy to cause misunderstanding. It does not trigger a return event; it accepts an event from the browser via ASP.NET and triggers a server-side .NET event. The unique purpose of this method is to convert the universal form return event sent by the browser to have named and meaningful .NET control events with useful parameters, other server-side controls can listen to the event, the page designer can be convenient Write the code for the event. If you think it as AcceptPostBackandOptionAlyraisServere, then you get the correct model.

I put some code in this naming method, and execute these code when the control receives the time from the user's browser (see Figure 10). AsP.NET calls this method and passes the Eventargument string to the client script by the client, which is passed to the client script then transferred by the client. In this example, the string is the text of the table cell of the user clicks. My sample code can analyze the line number and column number from the string, so the server-side handler knows which cells have clicked. If you know your control is the only thing that is paying attention to who leads to a return, you don't need to do it; just write the handler code in the appropriate position in the RaisePostBackevent method. However, your control is one of the main tasks required to be completed after returning is that some events have occurred on your control on other controls on your control.

To do this, your control needs to use the same general-purpose event handler to use the same general-purpose event handler in the Windows Form Control to excite the .NET event. In this example, I added a event called TablecellClicked to the control, which contains two parameters, click on the rows and columns, as shown in Figure 10. The handler can be installed for any of the required controls to receive the event. In my example, the page contains a handler that receives an event from the table control and sets the clicked cell to the tab control (see Figure 11).

In summary, event processing in the web form control includes two essential parts, and an optional third part. First, the render method of the control must generate client HTML, which causes the control to return to the control during the client. Second, your control must implement the iPostBackeVentHandler interface so that ASP.NET can notify you that it receives the post and passes additional information about it. Next is an optional section, your control can be (very likely to select) to stimulate the .NET event, so that other controls can receive the notification of these events that occur.

Back to top

View status management

The web page is inherently stateless. This means that the content displayed on a page is independent of the content of the user before, unless the code is associated. There is no big problem when the user just views a static text page. However, since most interactions currently related to the Web site involve continuous sessions across multiple pages, this will cause serious problems. The SDK document claims that you must "provide continuity to the user". Document authors analyze problems completely outdated. The user experience is the core of all, this is the Jinke Yusha. It should be to achieve the user's expectations through your code, not other ways. If your programming model does not match the user's needs, you must write code to make it consistent. The continuity of the user is true, the real fake phase is the continuity of the code.

The designer written on the ASPX page can access the SESSION and Application collection objects to maintain a state of a page to another page. But the control designer cannot use them because she doesn't know when the page is present, or the timeout is abandoned, or by the page programmer explicitly dump. In fact, she doesn't even know if it has opened the session state and cannot be changed when the session state is not opened. Therefore, if your control needs to be maintained between the other rendering of the page, other methods are required.

The .NET framework provides a mechanism that allows Web form controls to maintain their status safely and conveniently. The control base class contains a member called ViewState. It is a collection of attribute packets that are used in the same type of property packet collection used in the session and Application objects, which are in the hidden text fields stored on the page. You can see the view status in the hidden input field named __viewstate in Figure 8. When your control places the data into the view status collection, ASP.NET seizes it into the ViewState string and transmits it as part of the rendered page to the client. When the page is raised to the server, ASP.NET will extract hidden variables and reach it to the ViewState member variable of each control. This architecture is particularly advantageous to use the scalability when using the network field, because it avoids any type of server relationship. Any handling of the retraceable computer can see the last state and store it next time (may be updated).

I am writing my sample table control to use ViewState to remember the state, that is, the line and column of the user clicked. In the constructor of my control, you can see that I created view status variables used to memory clicked rows and columns and set them to -1, indicating that there is no option.

'Start Member Variables in Desired Default State;

'NO SELECTED CELL

Public Sub New ()

Me.ViewState ("SELECTEDROW") = -1

Me.ViewState ("SELECTEDCOLUMN") = -1

End Sub

When you receive a clicked return from the client (see Figure 10), I extracted the cell selected by the user and store it into the ViewState. When presenting (see Figure 9), I extracted selected rows and columns and adjust HTML to correctly display the selected cell. This is all the steps. Very simple?

Note that the base class contains a member variable called EnableViewState, which indicates whether it is notified whether the control is saved in the ViewState. However, if the sample code will be used, the variable is found to look without any effect. This is because the variable does not turn off the ViewState mechanism internally. It is just a Boolean flag for notification control: For the page designer, it is best to close ViewState in advance. Whether to write code to check and respond to the status of the variable, all care about your choice, in this case, I have chosen this. How is it to see someone in violation of the least amazed principle? So don't do this for your customers, ok?

Back to top

Client script

Most of the control functions previously happened in the server, in fact, many people refer to these web form controls as "server controls" to emphasize this. Really good Web UI design usually requires at least some of the code in some browser script forms on the client. For example, the verification program control in the Web Form Toolkit ensures that the user uses data that meets its conditions (any string, the integer between the valid email address, 5 to 15, etc.), then fills the required fields in the form, then Allow the submission of the form. If the data is not available to the verification program, the verification program will display an error message and aborted. This saves network bandwidth, server cycle, and prevents users from generating frustration, because feedback is immediate. This is the combination we want to see.

The ASP.NET framework provides a built-in function for web form controls that make it easy to send scripts to be placed in a page returned to the client, and conveniently access their own or other controls on this page. script. I have written an example program that shows that the control can be placed on the three locations of the script on the page returned to the client (see Fig. 12, Figure 13 and Figure 14). Figure 12 is a script for the sample application

The controls are used to place the script on the page in the Page member variable, which indicates the page where the control is located. The control can be placed on the page on the page with the Page.RegisterStartupScript method. This script will be executed when the page is displayed in the user's browser. This sample program only pops up a message box when displayed. You can also place a script block using the Page.RegisterClientScriptBlock method, which requires explicit calls from other script code on the page. The sample program will only pop up a message box when you click the text on the page.

Both methods accept two string parameters: the name of the script block and the script itself. If the two controls are trying to register a script using the same name, the page will ignore the second attempt. This means to avoid naming conflicts with other controls you have written by yourself, and the industry-level control should use the unique long name to avoid using a general short name, such as MyScript. If you want to find out if the script is registered before registering a script block, you can use the two methods on the PAGE object, namely ISClientScriptBlockRegistered and IsStartupScriptBlockRegistered.

The script you pass can be text, such as the script in this example. However, sometimes the script may be very long, just like a verification program. In this case, you may need to place the script into a separate file to extract at runtime. In this case, the script tag can be written to use the src property to point the script execution engine to the position of the script file, as shown below: