Wrox Professional Web Parts and Custom Controls with ASP.NET 2.0 phần 3 potx

45 379 0
Wrox Professional Web Parts and Custom Controls with ASP.NET 2.0 phần 3 potx

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Creating Custom Controls It would be helpful, then, if the custom controls were presented to the developer in a way that reflects these functional groups rather than just as a list of custom controls in a DLL However, these custom controls reflect the requirements for a single site — the book site It’s not hard to imagine that the organization supporting the book site might also support sites selling music CDs, DVDs, and other entertainment products Because these kinds of products have different information needs than books, these sites will use different custom controls to display product information and to search for products Furthermore, a site that loads the DVD-enabled versions of the custom controls won’t use the book-enabled versions As a result, it makes sense to create separate DLLs for the DVD, CD, and book custom controls This will result in separate projects for the book, CD, and DVD sites’ custom controls, for instance The customer information custom control has different considerations, however The customer information used on one site is the same for all the sites because customer information is defined at the organization level, rather than the site level As a result, the customer custom control will be common to all of the sites It makes sense then, to have the customer information custom control in a project by itself so that it will be compiled into its own DLL With the custom information control in its own DLL, any of the sites can load the customer custom control without loading other custom controls that the site won’t use As this case study suggests, you are always looking at the tradeoffs between keeping your DLLs small while ensuring that loading one DLL will also “pre-load” other custom controls that your application will likely be using While it would certainly be helpful if developers using your custom controls read your documentation (you did write the documentation, didn’t you?), developers prefer to figure out how to use your custom controls by looking at the IntelliSense drop-down lists and the Object Browser As you develop multiple DLLs, you need to start thinking about how you can organize the Web Parts when presenting them to developers in IntelliSense and the Object Browser Naming Conventions The first step in providing a level of organization beyond the library level is to use a naming convention for your custom controls and their libraries that reflects the functions that are important to the control’s users — the developers building Web pages For the bookstore site, names that describe the function of the part (such as BookSearch, BookDetailDisplay, and CustomerSearch) are more useful to developers than, for instance, names that describe the order that the parts were developed in (FirstWebControl), how recent the custom control is (NewBookSearch), or the developer who created the custom control (MyWebControl — which is what’s used in this book) Having said that, the major benefit that you can pass on to your users is to be consistent in the way that you name your custom controls (for example, the descriptive names used earlier specified the type of data first, and then the activity performed) If you put out new versions of your custom controls, you should either create a new library or append version-related information to the end of the name (such as BookSearchV2) Namespaces The next step is to consider using namespaces, especially if you have (or expect to have) a project with many custom controls Namespaces allow you to organize the custom controls within a project into meaningful groups — meaningful from the point of view of the developer using the custom controls For the custom controls that support the bookstore Web site, namespaces that divide the custom controls into Book, Customer, and Site groups would reflect the way that developers think about the controls 63 Chapter It may appear, in the IntelliSense lists, that your classes are organized into groups by the name of their project/DLL That’s an illusion Classes are always organized by the namespaces that they belong to By default, however, the namespace for each project is set to the name of the project It is because of these default values for namespaces that it appears that controls are organized into groups by project name By overriding the default namespace for a project you can provide a higher level of organization and group controls in different projects together You may want to have custom controls that have been created in different projects presented to the developer as a group For instance, if there will be multiple projects to support the book, CD, and DVD store sites, a different way of organizing namespaces might make sense Instead of dividing the custom controls into Book/Customer/Site namespaces, it might make more sense to divide the custom controls into Search/Information/Page namespaces with the Search custom controls from all the Web sites sharing a namespace Within the Search namespace, the custom controls could be divided into Book/Music/DVD namespaces Dividing your custom controls among libraries is a technical decision — you want to group the custom controls to reduce the number of DLLs that will be loaded at run time The organization of your custom controls by Namespace is a design decision — you want to group your custom controls in a way that makes life easier for the developers using your custom controls As with your naming convention, the namespace-based organization should reflect the way that developers think about using your custom controls The number of possible conventions is large One large conglomerate uses CompanyName.ProjectArea ComponentArea.ComponentSubArea.EntityName (For example, it assigns names like DVDSales CustomerMgmt.UserInterface.Input.Address.) Other companies use naming conventions that help organize their source code in whatever source code repository they use The company in the last example uses the parts of the control’s name as subdirectories within SourceSafe This means that the code for the Address custom control is found in a subdirectory nested five levels deep but it also means that the source code for any given control is easy to find — provided that developers understand the convention and follow it when naming their controls It would be an exaggeration to say that the naming convention that you use doesn’t matter (a good naming convention embeds key information about the control in the name), but the most important part of a convention is that it be used consistently The samples created for this book are in two namespaces: VB (for WebControls written in Visual Basic 2005) and CS (for the C# versions) This division reflects an important distinction for the audience of a NET programming book: C# developers will want to use the versions of the custom controls written in C#; Visual Basic 2005 developers will want the Visual Basic 2005 versions Coincidentally, this namespace division reflects the division of the libraries: The Visual Basic 2005 custom controls and the C# custom controls are in two different libraries These two namespaces are nested within the PHVWebControls namespace, which causes the two libraries to be displayed together in the IntelliSense drop-down lists This namespace represents the total audience, represented by the readers of this book To set the root namespace for a Visual Basic 2005 project in Visual Studio 2005: 64 Double-click the My Project entry in Solution Explorer to open the Property Pages for the project On the Application tab, set the Root namespace text box to the namespace you want to use for your project (see Figure 3-3) Creating Custom Controls Figure 3-3 For C# projects: Double-click the Properties entry in Solution Explorer to open the Property Pages for the project On the Application tab set the Default namespace you want for the project (see Figure 3-4) Figure 3-4 65 Chapter You can also get to these property pages by right-clicking the project (either Visual Basic 2005 or C#) and selecting Properties from the pop-up list Namespaces within the root namespace are set inside the code files for the custom control by using the Namespace keyword in Visual Basic 2005 and the namespace keyword in C# The following Visual Basic 2005 code shows the definition of a namespace called VB within a Visual Basic 2005 class file: Namespace VB Public Class BookDetail Inherits System.Web.UI.WebControls.WebControl End Class End Namespace For C#, the namespace is set like this: namespace CS { public class BookDetail : { } } System.Web.UI.WebControls.WebControl Extending Existing Controls The rest of this chapter shows you how to build all the parts of a custom control However, you don’t always need to take on that level of complexity Often what you want to is change one or two features of an existing control, or just add a new method For instance, if you haven’t databound the ASP.NET list box, adding items to it can be awkward As an example, this code adds some Canadian cities to a list box in Visual Basic 2005: Me.ListBox1.Items.Add(“Regina”) Me.ListBox1.Items.Add(“Ottawa”) Me.ListBox1.Items.Add(“Winipeg”) This isn’t the most awkward code in the world, but it would be convenient to have a method that would add all of the items in a single statement, like this in Visual Basic 2005: Me.PHVListBox1.AddList (“Regina,Ottawa,Winnipeg”) It’s very easy to take an existing control and add a new method to it Because this control is just modifying the existing list box control, simply have your custom control inherit from the ListBox object That’s what this Visual Basic 2005 code does: _ Public Class PHVListBox _ 66 Creating Custom Controls Inherits System.Web.UI.WebControls.WebControl.ListBox End Class As does this C# code: using using using using using using System; System.Collections.Generic; System.ComponentModel; System.Text; System.Web.UI; System.Web.UI.WebControls; namespace MyWebControlsCS { [ToolboxData(“”)] public class ListBox : System.Web.UI.WebControls.ListBox { } } This example demonstrates the power of inheritance With no additional code, this custom control will have all the methods, properties, and events of a list box The next step is to extend the list box by adding the new LoadList method As you write the code for this routine you can take advantage of all the methods of the base object that you’ve inherited from This means that you can leverage your knowledge of the methods and properties of the base object in writing your new code Adding the following Visual Basic 2005 to the class module creates a list box with all the features of the standard ASP.NET list box plus a new LoadList method As you can see, the code just takes advantage of the Add method of the underlying list box’s Items property: Public Sub LoadList(strList As String) Dim strValues() As String Dim strValue As String strValues = strList.Split(“,”) For Each strValue in strValues MyBase.Items.Add(strValue.Trim) Next End Sub In C#, the code looks like this: public void LoadList(string strList) {string[] strValues; strValues = strList.Split(‘,’); foreach (string strValue in strValues) { base.Items.Add(strValue.Trim()); } 67 Chapter If you want to ensure that you call the base version of a method or a property, you must use the MyBase object in Visual Basic 2005 or the base object in C# If you use the Me object (in Visual Basic 2005) or this object (in C#), you will call your overriding versions of these methods (if they exist) Once the control is in your Toolbox and dragged onto the page where it is assigned the ID of BetterListBox1, the LoadList method can be called like this in Visual Basic 2005: Me.BetterListBox1.LoadList(“Regina,Ottawa,Winnipeg”) Or like this in C#: this.BetterListBox1.LoadList(“Regina,Ottawa,Winnipeg”); Creating a Complete Custom Control While you are often able to create the control that you want by extending an existing control, sometimes there is no equivalent control for you to build on Even if you don’t intend to build a control from scratch, understanding all the options available to you in a custom control lets you more when extending a custom control These options include: ❑ Creating a control that consists of other ASP.NET controls ❑ Replacing existing methods and properties with your own versions ❑ Controlling all the HTML generated by your control ❑ Intermixing pure HTML and ASP.NET controls ❑ Controlling what your control does at design time in Visual Studio 2005 ❑ Managing your control’s style and appearance ❑ Extracting information about your control when it executes at run time This section walks you through the first two of these tasks The other tasks deserve sections of their own and are discussed later in this chapter There are two strategies you can follow when creating a custom control: ❑ Leveraging existing ASP.NET controls: In this strategy, you define your control by adding other controls (constituent controls) to it Most of the HTML generated for your custom control will be produced by these other controls ❑ Generating all the HTML yourself: Instead of counting on constituent controls to write out their HTML to create your control’s UI, you write all of the code that generates all the HTML for your control Let’s look at the constituent controls strategy first 68 Creating Custom Controls Adding Constituent Controls One strategy for creating a useful custom control is to add constituent controls to your custom control The customer information custom control, for instance, would contain several text boxes and labels Even if all you want to add to your custom control is plain text and HTML tags, you can so by adding HTML literal controls (although, as you’ll see when we discuss the Render method, using controls for just text and HTML may not be the most efficient method) The second strategy for creating a custom control, writing all the HTML yourself, is covered later in this chapter Using the CreateChildControls Method Controls are typically added to the custom control in the CreateChildControls method The CreateChildControls method is built into the WebControl object, but you should replace it with your own version of the method in order to add the controls you want to your custom control Most of this chapter deals with your custom control and the constituent controls as objects While an object-oriented approach is a useful way to work with custom controls in code, the reality is that — in the end — your custom control will be turned into HTML and text in a Web page, and displayed in a browser The process of converting your custom control object into HTML and text is referred to as “rendering.” In this section, rendering is handled for you using methods built into the WebControl object and the constituent controls Later in this chapter you’ll see how you can take control of rendering your controls ASP.NET automatically calls your version of the custom control’s CreateChildControls method In the method you should add your constituent controls to the Controls collection provided by the WebControl object The constituent controls will have their HTML automatically rendered to the host page by ASP.NET as part of rendering your custom control The process that you follow in the CreateChildControls method is simple: Create an ASP.NET control Set any properties on the control Add the control to the WebControl object’s Controls collection This Visual Basic 2005 code adds two HTML literal controls and a text box to the custom control The HTML literal controls are used to add HTML breaks and text into the custom control’s output, while the text box provides a fully functional ASP.NET server-side control with all of its methods and properties: Protected Overrides Sub CreateChildControls() Dim lt As LiteralControl Dim txt As System.Web.UI.WebControls.TextBox lt = New LiteralControl(“Value: “) Me.Controls.Add(lt) txt = New System.Web.UI.WebControls.TextBox txt.Text = “Hello, World” txt.ID = “txtInput” 69 Chapter Me.Controls.Add(txt) lt = New LiteralControl(“”) Me.Controls.Add(lt) End Sub In C#, you use this code: protected override void CreateChildControls() { LiteralControl lt; System.Web.UI.WebControls.TextBox txt; lt = new LiteralControl(“Value: “); this.Controls.Add(lt); txt = new System.Web.UI.WebControls.TextBox(); txt.Text = “Hello, World”; txt.ID = “txtInput”; this.Controls.Add(txt); lt = new LiteralControl(“”); this.Controls.Add(lt); } The resulting custom control, in a WebPartZone, is shown displayed in a browser in Figure 3-5 Figure 3-5 The presence of the Overrides keyword (in Visual Basic 2005) or the override keyword (in C#) in the method definition causes your method to be called in place of the base method provided by the WebControl object You can also use Shadows (in Visual Basic 2005) or new (in C#) instead of Overrides/override to create a new version of the base method This allows your version of the routine to be different from the base routine (for instance, to replace a read-only property with a read/write property or change the 70 Creating Custom Controls datatype/number of parameters for a method) It’s an unusual situation where you can replace a base method with a routine that has different characteristics and have your new method function effectively in the control framework In Visual Studio 2005, you can create a routine that overrides a method or a property by typing the word “overrides” (in Visual Basic 2005) or “override” (in C#) IntelliSense will then pop up a list of methods and properties that you can override Pick the one that you want and Visual Studio 2005 writes out the skeleton of the routine for you You can also add controls to your Controls collection by using the WebPart’s AddParsedSubObject method This method, when passed a reference to a control, will add it to the Controls collection This Visual Basic 2005 code adds a WebForm list box and text box to the Control’s collection along with an HTML Button: Protected Overrides Sub CreateChildControls() Dim lb As New WebControls.ListBox Dim tb As New WebControls.TextBox Dim btn As New HtmlControls.HtmlButton Me.AddParsedSubObject(lb) Me.AddParsedSubObject(tb) Me.AddParsedSubObject(btn) End Sub In C#: protected override void CreateChildControls() { WebControls.ListBox lb = new WebControls.ListBox(); WebControls.TextBox tb = new WebControls.TextBox(); HtmlControls.HtmlButton btn = new HtmlControls.HtmlButton(); this.AddParsedSubObject(lb); this.AddParsedSubObject(tb); this.AddParsedSubObject(btn); } You can access the controls in the Controls collection to set their properties Controlling the Display When you drag your custom control onto a Web page, your constituent controls may not display The CreateChildControls method is not automatically run at design time Always check the display of the page with your custom control in the browser — that’s the display that matters To put it another way, the code that you write is primarily intended to control the run-time behavior of your control The design-time behavior of your custom control won’t always match the run-time behavior of your control 71 Chapter To ensure that your constituent controls are displayed at design time, you can call the CreateChildControls method from methods or events that are run at design time However, there are two potential problems: ❑ Your CreateChildControls method is automatically called by ASP.NET after you call the method, causing your controls to be added twice ❑ Depending on when you call the CreateChildControls method, ASP.NET may already have called the method so that your call will add the constituent controls a second time There is a simple solution to this problem First, at the end of the CreateChildControls method, set the ChildControlsCreated property to True This is used by ASP.NET to signal that the CreateChildControls method has executed If you set the property in the CreateChildControls method, you ensure that ASP.NET will not call the method a second time Second, you should never call the CreateChildControls method directly Instead, you should call the WebControl object’s EnsureChildControls method This method first checks the ChildControlsCreated property and won’t call the CreateChildControls method if the property is set to True This Visual Basic 2005 code calls the CreateChildControls method from the control’s Init event (the Init event is called at design time) At the end of the CreateChildControls method, the ChildControlsCreated property is set to ensure that the method is not called a second time: Private Sub BookDisplay_Init(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles Me.Init Me.EnsureChildControls() End Sub Protected Overrides Sub CreateChildControls() Dim txt As New WebControls.TextBox txt.ID = “fred” txt.Text = “Hello, World” Me.Controls.Add(txt) MyBase.CreateChildControls() Me.ChildControlsCreated = True End Sub This C# code does the same thing: Private BookDisplay_Init(object sender, EventArgs e) { this.EnsureChildControls(); } protected override void CreateChildControls() { WebControls.TextBox txt = new WebControls.TextBox(); txt.ID = “fred”; 72 Creating Custom Controls If you add HTML to the page by overwriting the TagKey property and AddAttributesToRender method, then you must use postback to gather the data that is sent back to the server for your control However, implementing this postback processing isn’t necessary if you create a control using nothing but constituent controls (though you can still use postback processing) Data in constituent controls can be retrieved through their properties (for example, the Text property of a TextBox control) rather than through the postback interface To gather the data returned by the browser, you can implement the LoadPostData method This method is called when the data is returned to the server and provides access to the data sent back from the browser However, the LoadPostData method is called only if you let the Page object know that you will process posted data You notify the page that you will be processing postback data by calling the Page’s RegisterRequiresPostBack method, passing a reference to your custom control This Visual Basic 2005 code calls the RegisterRequiresPostBack method, passing a reference to the control This could be used either with the previous code, which used the TagKey property to create the control’s HTML, or with the CreateChildControls method, which added constituent controls to the Controls collection: Private Sub BookDisplay_PreRender(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles Me.PreRender Page.RegisterRequiresPostBack(Me) End Sub In C#: private void BookDisplay_PreRender(object sender, System.EventArgs e) { Page.RegisterRequiresPostBack(this); } Now that the control is registered for postback processing, you can add the IPostBackDataHandler interface to your control and implement the LoadPostData method The LoadPostData method is passed two parameters: the name of your custom control on the page (the postDataKey parameter), and a collection of data from the page (the postCollection parameter) This Visual Basic 2005 code would be used in a control that overrides the TagKey property so that you can retrieve the data posted back from the control (the class declaration is included to show the IPostBackDataHandler interface): Public Class BookDisplay Inherits System.Web.UI.WebControls.WebControl Implements IPostBackDataHandler Dim strTextBoxData As String Public Function LoadPostData(ByVal postDataKey As String, _ ByVal postCollection As Collections.Specialized.NameValueCollection) _ 93 Chapter As Boolean Implements IPostBackDataHandler.LoadPostData strTextBoxData = postCollection.Item(postDataKey) End Function End Class In C#: public class BookDisplay : System.Web.UI.WebControls.WebControl, IPostBackDataHandler { string strTextBoxData; public bool LoadPostData ( string postDataKey, System.Collections.Specialized.NameValueCollection postCollection) { strTextBoxData = postCollection (postDataKey); } At the very least, you want to retrieve this data so that it can be used when the page is rendered and sent back to the user Tags that are generated through the TagKey method not have their data automatically copied to the page that is sent back to the user In other words, if you don’t set the value attribute of an input tag generated through the TagKey, the user’s data will be lost when the page is re-rendered In the previous example, the data was retrieved into a module-level variable called strTextBoxData That variable should be used in the AddAttributesToRender method to cause the user’s input to be displayed in the text box when the page goes back to the browser, as this Visual Basic 2005 code does: Protected Overrides ReadOnly Property TagKey() As System.Web.UI.HtmlTextWriterTag Get Return HtmlTextWriterTag.Input End Get End Property Protected Overrides Sub AddAttributesToRender( _ ByVal writer As System.Web.UI.HtmlTextWriter) MyBase.AddAttributesToRender(writer) writer.AddAttribute(HtmlTextWriterAttribute.Name, Me.UniqueID) writer.AddAttribute(HtmlTextWriterAttribute.Type, “text”) writer.AddAttribute(HtmlTextWriterAttribute.Value, strTextBoxData) End Sub In C#: protected override System.Web.UI.HtmlTextWriterTag TagKey { get 94 Creating Custom Controls { return HtmlTextWriterTag.Input; } } protected override void AddAttributesToRender(System.Web.UI.HtmlTextWriter writer) { base.AddAttributesToRender(writer); writer.AddAttribute(HtmlTextWriterAttribute.Name, this.UniqueID); writer.AddAttribute(HtmlTextWriterAttribute.Type, “text”); writer.AddAttribute(HtmlTextWriterAttribute.Value, strTextBoxData); } However, for a control that contains constituent controls, you will want to retrieve the value of your constituent controls Those values are also in the data collection and can be retrieved by using the name of the constituent controls Unfortunately, the Controls collection of your custom control isn’t loaded at the time that the LoadPostData method is called, so you can’t retrieve the constituent control ids from that collection (the LoadPostData method is called after the Init event and before the CreateChildControls method when the Controls collection is re-built) Instead you must provide the name of the constituent control concatenated with the custom control’s UniqueId and IdSeparator properties The following Visual Basic 2005 code builds on the previous CreateChildControls method to process the data for the TextBox constituent control after it is returned from the browser The code uses the same id assigned to the TextBox in the CreateChildControls method to retrieve the browser data from the data from the postCollection collection: Dim strTextBoxData As String Public Function LoadPostData(ByVal postDataKey As String, _ ByVal postCollection As Collections.Specialized.NameValueCollection) _ As Boolean Implements IPostBackDataHandler.LoadPostData strTextBoxData = postCollection.Item(postCollection[Me.UniqueID & Me.IdSeparator & “MyTextBox”) End Function In C#: string strTextBoxData; public bool LoadPostData ( string postDataKey, System.Collections.Specialized.NameValueCollection postCollection) { strTextBoxData = postCollection[this.UniqueID + this.IdSeparator + “MyTextBox”]; } 95 Chapter You can fire events as part of your postback processing to signal to server code in the page that some condition has occurred in your custom control Raising custom events is discussed in Chapter Controlling Related HTML Regardless of which strategy you follow for creating custom controls, managing the HTML for your control is obviously a key part of creating a custom control The HTML that is generated by your custom control is your control when it finally appears in the browser In addition, if you intend to write client-side code that interacts with your custom control (discussed in Chapter 9), you need to be familiar with the HTML generated for your custom control This section walks you through the HTML and gives you some additional ways of controlling the HTML generated for your custom control In addition to the tags and text generated within your custom control, there are two other sets of tags and text that you need to consider: ❑ The tags that are added to your Web page at design time when a developer wants to use your control ❑ The HTML generated around your custom control at run time When ASP.NET renders your custom control, it encloses the control that you render with some additional HTML to manage your control on the page (For instance, by enclosing your control in a tag, ASP.NET can assign style properties to the tag that will control the appearance of your custom control’s HTML in your browser.) In addition, you can specify some of the HTML to be used with your custom control as part of defining the class for your custom control Design-Time HTML When a custom control is dragged to the page, two tags may be added to the page: ❑ The tag for the control itself: This tag is always added ❑ A Register directive: This tag is added the first time that a custom control from a particular DLL is added to the page Subsequent controls from the same DLL will be based on the first Register directive The Tag for the Control Handling the tag used for the control at design time is straightforward: You just use the ToolboxData attribute on the class module for your control The ToolboxData attribute lets you specify the design time tag generated for the control when a developer drags your custom control from the toolbox and onto the page: Public Class BookDetail Inherits System.Web.UI.WebControls.WebParts.WebControl 96 _ Creating Custom Controls This C# code does the same: using System; [ToolboxData(“”)] public class BookDetail : System.Web.UI.WebControls.WebParts.WebControl At run time, the {0} is replaced with the namespace prefix for the control (the namespace for the control is discussed in the next section) For instance, the resulting design time tag might look like this, assuming that “cc1” is used as the prefix for the custom control: At run time, this tag is replaced with the HTML generated by your custom control (along with whatever HTML ASP.NET wraps around your custom control) The Register Directive The Register directive is added at the top of the page and defines the namespace and prefix to be used with all the custom controls from the DLL By default, if no namespaces have been specified in the project, the namespace will be the name of the project The prefix used with the tags defaults to “cc” and some numeric value to distinguish the custom controls drawn from different libraries As an example, this is the Register directive that is generated when a control from the MyWebParts project is dragged to the page from the toolbox (and is the first Register directive added): The tag generated at design time for a custom control called BookDetail from the MyWebParts project looks like this: By using the TagPrefix attribute you can control the prefix used when the Register directive for your custom control is generated The TagPrefix attribute appears before the class definition for your control and accepts two parameters: the namespace (which must match the namespace set in the code for your control) and the prefix This Visual Basic 2005 example applies the prefix myc to a custom control whose root namespace is set to MyControls: _ Public Class BookDetail End Class In C#: [assembly: TagPrefix(“MyControls”, “myc”)] public class WebCustomControl1 : WebControl { } 97 Chapter The Register tag and the tag for the custom control that is generated by Visual Studio 2005 when the control is dragged to the page look like this: Run-Time HTML The ToolboxData attribute also allows you to control what HTML will be placed in the page at run time For instance, this Visual Basic 2005 example causes the HTML to create a red border, pixel wide around the control: Public Class BookDetail _ In C#: using System; [ToolboxData(“”)] public class BookDetail : System.Web.UI.WebControls.WebParts.WebControl The resulting HTML in the page delivered to the browser looks like this: Setting Attributes If the constituent controls for your custom control were written out by the default Render method, they will be enclosed by a tag: constituent controls The WebControl object gives you two ways to alter the attributes on the tag that encloses your custom control’s constituent controls and on the constituent controls themselves: the Attributes property and the AddAttributesToRender method Many of the attributes generated at run time can be managed through property settings on the controls However, not all the attributes that are available in the HTML specification are available as properties on your custom control or its constituent controls The techniques that are described in this section enable you to go beyond the properties exposed by the ASP.NET controls 98 Creating Custom Controls The simplest method for adding attributes is to use the Attributes property on the WebControl object, which allows you to add arbitrary attributes to the tag for a custom control that uses the default Render method Modifying the tag allows you to control the way that all the constituent controls within the custom control are handled by the browser For instance, the HTML generated for the book detail control, when it’s displayed in the browser, looks like this:

Ngày đăng: 06/08/2014, 09:20

Từ khóa liên quan

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan