Understanding Templates in ASP.NET

xiaoxiao2021-03-06  51

Download The Code for this article: cutting0201.exe (713KB)

Web server controls can be customized by setting properties or by using CSS styles. Some allow you to customize their look through ASP.NET templates. An ASP.NET template is a mix of HTML elements and ASP.NET controls that make up the layout for a particular area of ​​the control. Templates are not the same as styles. Styles primarily refer to CSS stylesheets and affect graphical properties such as colors, font, border style, cell spacing, and so forth. With styles, the control's layout remains unchanged in ITS Structure But Can Be Modified in Its Appearance.in Contrast, Templates Involve Deeper Changes That Modify Some Portions of A Control '

s user interface. For example, the Repeater control allows you to use a combination of HTML elements and ASP.NET controls to define the layout for each row in the bound data source. Likewise, the DataGrid control lets you format the cells of an entire column of data by using any valid combination of ASP.NET controls. In addition, the DataGrid control supports customization of rows by applying different templates to individual rows, alternating rows, selected rows, and so on.The overall pattern behind ASP.NET templates is not very different from that in the visual styles of Windows® XP or even Windows common controls. The key point to understand is that certain parts of a given user interface element can be customized. You have client and non-client parts in Win32® common controls, control-specific parts in Windows XP styles, and control-specific templates in certain ASP.NET server controls. in Win32, messages are used to let programmers get involved with the painting process. in Window s XP, the theme manager calls the piece of code registered to paint part of a given control. In ASP.NET, control classes that inherit the ITemplate interface can dynamically build pagelets and insert code into the main page as raw HTML.Styles and templates are not mutually exclusive. You can use styles and templates together, or use them separately to control the appearance of the elements defined within your templates. When the templated control (say a DataGrid) is processed, templates are instantiated in the containing page and rendered In html.in this column, i '

ll cover ASP.NET templates with respect to the features provided by the three iterative controls:. Repeater, DataList, and DataGrid They all support templates to increase their own level of flexibility and to help you customize the graphical presentation of your data In addition. , I'll illustrate a few techniques for loading templates programmatically and discuss how they could be applied to create a multi-selection DataGrid control. In all the examples, I'll be using the Employees table of the SQL Server ™ 2000 Northwind database. What is a Template, Anyway? Generally speaking, a template is the description of how a certain element will be rendered at runtime. In ASP.NET, a template is property of a server control that describes the static HTML, controls, and script to render within one region of the control. For example, a Repeater control has a HeaderTemplate property that defines the contents of its header region. You normally define a template within the body of an ASP.NET page using Declarative syntax. for example, the fold code shows how to specify a template to draw the header and each row of a reteater control.

Employees

...

When it comes to rendering the contents of the Repeater control, the ASP.NET runtime uses the content defined in the templates and processes it-often together with bound data-to create an HTML representation of the region. All the server-side controls within the template individually render themselves as HTML.The Microsoft® .NET Framework utilizes the ITemplate interface at runtime to process the templates into a control hierarchy that can be databound and rendered to populate a part of an ASP.NET control. As long as you define templates in a declarative manner-using inline tags in ASPX pages-you do not strictly need to know about the ITemplate interface. That will become important only when you move one step further and start investigating how to create and assign templates programmatically and dynamically. But Before WE LOOK AT THAT, Let's Review The Use of Templates with a DataGrid Control.DataGrid's Templated ColumnTemplate-Based Column in A Web DataGrid Control Play An Important role as they allow you to add a freeform column type to the DataGrid. Normally, the DataGrid control displays all of its contents through plain text strings (as BoundColumns), or through one of the pre-defined column types. However, sometimes the pre -Defined coluMn Types Just Don '

t provide the representation the page developer is after. A templated column can define up to four different templates, as explained in Figure 1. You will likely use the ItemTemplate most frequently. It defines how the nth cell of the column will draw and what its contents will be in terms of constituent controls. HeaderTemplate and FooterTemplate are rather self-explanatory. The EditItemTemplate property lets you specify how the cell will change when the parent row is put into edit mode. Note that, unlike the DataList control, the DataGrid does not feature a template for the selected state.Your DataGrid control should use template-based columns when you need to do something in a nonstandard way throughout the whole column. If you need to display data in a way that none of the base column types provide For (Text, Buttons, Hyperlinks), Templated Column Are Your Best Choice.The Following Code Shows How To Bind A Templated Column To A DataGrid Control.

... ASP.NET LAYOUS HERE ...

Notice that a templated column, like any other column type, can have a header text as well as a sorting expression. Templated columns, though, do not have an explicit data source field to bind to. Among the members of the TemplateColumn class, you will not find any DataField or DataTextField property.The lack of an explicit data-bound property is justified by the extreme flexibility that is the ultimate goal of such a column layout. To render a column, you could use, say, a Label control that does have the Text property, but also a dropdown list control or an image, both of which do not have anything like the Text property. As a result, you must always use data binding expressions to bind to data. While they're often too verbose in my opinion, they also give you unprecedented flexibility.The following code snippet represents valid content for an item template:

/>

By using DataBinder.Eval, you can access any field in the currently bound data source. In addition, you can combine them in any order to obtain any sort expression that's otherwise impossible using a simpler bound or button column.Figure 2 ColumnIn Figure 2, you can see a sample template-based column in which simple HTML formatting has been applied to a couple of database fields This result can not be obtained with per-field, non-template-based binding The item template code looks like the following..:

<% #

""

DataBinder.eval (Container.DataItem, "Lastname")

, "

DataBinder.eval (Container.DataItem, "firstname")

%>

If you need to combine more fields in the same displayable format, templated columns are the only way to go. If you need to apply any special formatting or feature to the cell, you are better off hooking to the ItemCreated or the ItemDataBound grid events. for example, if you need to change the background color of a cell, or any other style property based on a condition, you write a handler for ItemCreated, make sure the item being created is exactly of the type you need ( typically Item or AlternatingItem), and then merge new and existing styles. When the ItemCreated event fires, though, there is no guarantee that the item has been bound to data already. The data is normally available through the DataItem property of the event data structure . For the datagrid's itemcreated Event, this Structure IS DataGriditeMeventArgs.void Itemcreated (Object Sender, DataGriditeMeventArgs E)

The expression e.Item.DataItem evaluates to the data associated with the item being created. If the grid binds to a DataTable, then DataItem is a DataRow object. As I mentioned earlier, though, in most cases the data binding has not yet occurred at the time the ItemCreated event fires. in fact, data binding normally takes place when the ItemDataBound event is raised. This rule has just one exception regarding template-based columns. A templated column is not explicitly bound to a single field in the data source ;.. it can access the whole data item This can be done during ItemCreated without waiting for ItemDataBound, which is an event that fires later than ItemCreated for bound, button, and hyperlink columns, you will need to hook the ItemDataBound event to preview the data-bound text that the grid is going to display.Templated HeadersSince the TemplateColumn class allows for a HeaderTemplate property, you can also customize the header (and the footer) of a given column. Speaking of ad vanced customization, there is an important point to be made here. You can never have plain data-bound columns with a templated header or footer. Templates apply only to instances of the TemplateColumn class. For instance, if you want to edit the contents of a column in a nonstandard way (let '

s say you want to add some validators), then you have to use templates throughout, even though the column renders well with the simpler BoundColumn class.Changing the layout of the header, though, can be problematic if you need to sort that column by a certain expression. The sorting mechanism is triggered by a hyperlink control that the DataGrid control automatically embeds in the column heading. The href property of this hyperlink control generates a postback event when the user clicks on the element. The target of the hyperlink is client -side JavaScript whose internals have not yet been fully documented with ASP.NET Beta 2. Feel free to change the layout of a column heading as long as you do not need sorting. If you do need it, use the ItemCreated event to add extra controls to the header and leave the DataGrid control free to generate everything that is needed for sorting.The code in Figure 3 dynamically adds a dropdown list to the header of a template column to let you choose the e xpression to sort by. Customizing the header is useful when you have templated columns that group together several fields. In this case, you might want to allow users to sort by a variety of fields, as shown in Figure 4.Figure 4 Sort by FieldThe code in Figure 3 creates a dynamic dropdown list with the available sort expressions. Next, it retrieves the currently selected expression when users click on the header's hyperlink. The header text of the template column must be set to a non-empty string so that all The Standard Infrastructure for Sorting Can Be Built and Set Up To Work Properly.

Sortexpression = "*">

Notice the unusual value (an asterisk) assigned to the SortExpression property. It plays a key role since it allows the sort command handler (see Figure 3) to recognize that the user clicked on a column that requires special treatment for sorting. The SortExpression attribute , in fact, is the only element you have to recognize the clicked column.Figure 5 Grouping ColumnsIn Figure 5 you can see another special type of column header-one that groups two or more physical columns. This solution turns out to be rather useful when you have templated columns of data where alignment is important In particular, the sample utilizes this trick to align the title of courtesy with first and last name The grid contains two distinct columns:.. one BoundColumn for the title of courtesy and one TemplateColumn for the Employee name. Both Columns Have the the in The side column. Which cell you remove is up to you.// 1 means second column in the gridell = (TableCell) E.Item.cells [1];

E.Item.cells.Remove (Cell);

Cell = (TableCell) E.Item.cells [1];

Cell.columnpan = 2;

Adapt UI to Data Template-based columns help considerably when you want to model the control's user interface to accommodate the actual data to be displayed. Not all data in a data grid would be easy to read and understand if rendered as plain text. This is particularly true for Booleans, arrays, and images. Depending on their real meaning and role in the context of the application, Boolean data can be better rendered as a pair of mutually exclusive Yes / No strings or with small pictures representing checked and unchecked controls. Using pictures instead of a true checkbox control is more effective because the image is not clickable and never takes the focus, which results in a more natural user interface (see Figure 6) .Figure 6 Column with CheckboxesThe ImageUrl property of the Element is data-bound and can be associated with a binding expression.

ImageURL = '<% # getProperfile ((int)

DataBinder.eval (Container.DataItem,

"PAID"))%> '

/>

In this code, the binding expression consists of a user-defined function that takes the value of a Boolean field as an argument. The function returns the name of the proper GIF file to be used within the resulting HTML tag.Sometimes, though, the ideal representation of Boolean data may not require two mutually exclusive images or text. For example, a column that will represent whether a given invoice has been paid can be effectively rendered through a checkmark if the field evaluates to true and to nothing if it has not. in this simple case, you could elegantly solve the issue by intercepting the cell creation through the ItemDataBound event. The code needed to do this is shown in Figure 7, while Figure 8 shows the results.Figure 8 Column with Checks In general, if you can work around the data representation issue and do without template-based columns, then by all means do so. Templates are powerful and effective, but using them is always a bit heavier than hooking events like Ite mDataBound and ItemCreated. In terms of raw performance the difference between the two approaches is probably not very meaningful for most applications. In short, always choose the most flexible solution with a preference for event hooking.The code in Figure 7 addresses an interesting point that is even more evident if the information to be displayed in a given column consist of images. What could you do if, for one reason or another, the image for one row is not available? you might want to show some alternate text or simply leave The Cell Blank. To INSERT IMAGES IN A Column There Are Two Possible Approaches: You Can Either Write a New Column Object Or You Can Use A Templated Column Based on AN

element. The former approach is preferable because all the details will be hidden from view and buried in the class code. A new type of column would also be the right place to implement special features like an alternate layout to be used when the necessary image is missing or just will not render. Likewise, an image column could be adapted to load the bits, and not the path, of the image directly from a blob database field. I'll reserve this particular topic for a future column. In the meantime, let's look at how to show images and text in the same column using templates. As you will see, the technique is generic and can be employed with any column where two or more layouts can be applied, depending on runtime conditions.The idea is to define two layouts within the same template column, but display only one at a time. The layout to display can be decided either in the ItemCreated event handler or through a simpler data binding expression. Figure 9 shows the ASP.NET code for the DataGrid control that employs such a template The item template has an and an .. element Both explicitly assign their respective Visible property The label control features fixed text Normally, you should avoid using labels with static text... When the text is not expected to change, you are better off using client-side HTML elements like that are not marked to work on the server (they have no runat = server attribute). In this case, though, the value For the Visible Property Must Be Evaluated on the Server, So Using

is a necessity whether it features static text or not.The visibility of the controls representing mutually exclusive layouts for the column is controlled by a user-defined function called IsImageAvailable.bool IsImageAvailable (String strLastName) {

String strimagefile = "images //";

Strimagefile = strlastname ".bmp";

Return file.exists

Server.mappath (strimagefile);

}

The function assumes that the images to display are BMP files located in the Images subfolder of the app path and are named for the last name of the employee. Of course, this is clearly arbitrary. In your own applications you might use smarter solutions. But you get the point. Figure 10 shows what the final page will look like when some images are missing from the collection.Figure 10 Missing ImageLoading Templates ProgrammaticallyNormally, templated columns have their layout code defined at design time. While this remains the most common circumstance, there might be situations in which using design-time templates is just not the best solution. If you know in advance that a lot of changes must be applied at runtime through events like ItemCreated and ItemDataBound, there is no reason to define a static template forcing The Control to Support A Double Effort, Processing The Template First and The Changes next. Another Relativeness Frequent Situation In Which a Dynamic Template IS Preference le is when users must be able to change views of the same data.You can load templates dynamically in at least two ways. First, you can store the layout code of the template in a user control file, save it with an ASCX extension, and load it back through the LoadTemplate method of the Page object. The second alternative requires you to create a tailor-made class which implements the ITemplate interface. Let's look at both in more detail.To create a DataGrid column dynamically, you create a new instance of the specified class, populate its properties as appropriate, and then add the object to the DataGrid's Columns collection property The following code demonstrates how to proceed.TemplateColumn bc = new TemplateColumn ().;

Bc.Headertext = "Template Column"; bc.ItemTemplate = page.loadTemplate (TemplateFile);

Grid.column.add (bc);

First, you create a new instance of the TemplateColumn class and set the header text and other properties as required for your application. The tricky part is how you specify a template for ItemTemplate and any other template property you may need. The simplest way is through an external ASCX file. ASCX files are user controls that declaratively define the HTML text and the ASP.NET controls that form the template. The following is the typical structure of a valid ASCX file. <% @ Language = "C #"%>

<% # layout goes here%>

It is extremely important that you explicitly indicate the language used throughout the pagelet. You have to do this even though nothing in the ASCX code seems to be language-dependent. You can use any .NET-compliant language and even a language different from the one used within the host page.The Page.LoadTemplate method can be used to load the layout code for any template property of the column, including EditItemTemplate and HeaderTemplate. You do not need to use a fully qualified Web path when calling LoadTemplate because the method expects to receive a virtual path. You can not specify an absolute path with directory information.Templates from StringsUnlike many other methods that accomplish similar tasks, the Page.LoadTemplate method does not support streams and writers. If this were possible at all, then in -Memory strings could beneu used to create Dynamic Templates. If you don't want you, how to make your application, How can you create ATE DYNAMIC TEMPLATES? TYPICALLY, You DON '

t want to deal with ASCX files when the layout code is just one of the configuration parameters of the application all stored, say, in a SQL Server-based table or an XML file.Is there a way to dynamically create a template from a string ? Looking at the programming interface of the involved classes, the answer is certainly no. However, nothing really prevents you from creating a temporary file and loading a template from there. When you create temporary files from within an ASP.NET application, make sure that the file name is really unique for each concurrent session. for this purpose, use the Session ID or create a unique temporary file through the static method Path.GetTempFileName. Bear in mind, that the template file must have an .ascx extension. Also , as mentioned earlier, the LoadTemplate method assumes that the file has a virtual path and returns an error if you force it to work on absolute paths. On the other hand, stream and writer classes require absolute paths and do not know . How to cope with virtual paths As a result, you need code like the following to create and load a string-based template: TemplateColumn bc = new TemplateColumn (); String tmp = Session.SessionID ".ascx";

Streamwriter Sw;

SW = new streamwriter (server.mappath (tmp));

SW.WRITE (StrLayoutcode);

SW.CLOSE ();

bc.ItemTemplate = page.loadTemplate (TMP);

Grid.column.add (bc);

File.Delete (Server.MAppath (TMP));

You need to use Server.MapPath to map a URL from a virtual to a physical path, but only when working with streams and files.Implementing ITemplate If you want to create a template completely in memory, you have to first code and then instantiate a class which implements the ITemplate interface. The ITemplate interface has only one method, which is called InstantiateIn. Any template property in all ASP.NET server controls is exposed as a property of a class that implements the ITemplate interface. This interface simply defines the method used to populate the user interface of certain ASP.NET controls with child controls set out in accordance with a template Figure 11 shows the most interesting part of the code;.. it creates an in-memory templated column for a DataGrid control incidentally, nearly Identical Code Can Be Used for Datalist and Repeater Controls. The Only Difference Is The Type Casting Done in The onDatabase. The Structure of the Class You Have To Write Looks Lik E: Class lastfirstnameTemplate: itemplate {

Public void instantiatein (Control Container)

{...}

Private void BindlastName (Object S, Eventargs E)

{...}

Private void BindfirstName (Object S, Eventargs E)

{...}

}

The class can be defined in the