C#+asp.net 2.0 Advanced chapter of the custom composite component

Source: Internet
Author: User
Tags contains final functions implement interface reference client
Asp.net| Advanced One, increase the Enhancedlistbox client function

In order to use client code to implement the reordering of items in Enhancedlistbox, you must use JavaScript scripts and attach them to the Enhancedlistbox two buttons. For this reason, I suggest you use the "think back" approach. Just like writing an old-fashioned ASP's previous Web page, first write some JavaScript that generates HTML files. The best way to do this is to run the control, then observe its source code and copy its HTML to an editor, and then add JavaScript. Listing 2 (see download source code) shows the original form of JavaScript you need to add to your control. Then, with the help of Stringbuilder/stringwriter technology (Reference source list 3), the control builds this part of the code. The JavaScript code consists of a two-part function: To receive an HTML control (in this case, a <select> control), to use the Select Index, and to move it up or down in the list (basically the same as I did with server code at the beginning of this article). Now, you have to understand where you add the JavaScript code to the Web control. In order to implement multiple Enhancedlistbox controls on a Web form, the JavaScript code is not duplicated. You need to output it using the RegisterClientScriptBlock method of the Page.clientscript object.

To make this method work, you must call it in the overloaded OnInit event (see listing 4 in source code).

Finally, to make the button work correctly, you need to attach the added client method to it. In the code in Listing 1, you'll see a reference to a method renderbuttons. Although I did not list the code here (refer to the source in this article), it is able to use the technology generation button I described in my previous article. At that time, before the actual HTML tag was generated, the label properties were stored in stacks using the AddAttribute method. Here, you use the same technique to attach the client method to your button.

String s_moveup = "Moveitemup (document.all." +this. ClientID + ");
Output. AddAttribute (Htmltextwriterattribute.onclick,s_moveup);
Remember, Moveitemup is one of the JavaScript functions you've written successfully. The code will store these JavaScript commands on the stack before generating the buttons for sorting. For down buttons, you use the same technique. Note that I use ClientID to represent the ID of the generated control, but when the control is inside a composite control, this property should consider using the parent control's name.

You can now successfully apply the control to a Web form. You can add items to it in the same way that you manipulate a standard listbox control.

In fact, this is a drop-position placeholder (or asp.net listbox control) entirely. When you use the Reorder button, you will see that the items in the list change the order accordingly. Now let's make a note of this problem first. If you drag a button onto a Web form (you don't need to add code for it) and perform a postback, what do you think will happen? Exactly as I have described before; any reordering changes you make with the Reorder button will revert to the state that the control looks like before the most recent postback. So let's revise the question.

First, I'll add some JavaScript (source list 5). Note that this part of the code is added to the overloaded OnInit method and built using the stringbuilder/stringwriter technique, and the name of the JavaScript method is builditemlist. This function is responsible for building a string description of the full contents of the list box and placing the string in the Value property of an HTML element to be passed to the function. You can think of this as a serialization of the contents of a list. The serialized output style will vary according to your own design. Calling this JavaScript function requires attaching to other code on the button.

String s_moveup = "Moveitemup (document.all." + this. ClientID + ");";
String s_builditemlist = "Builditemlist (document.all." + this. ClientID +
", document.all.__" + this. ClientID + ");";
Output. AddAttribute (Htmltextwriterattribute.onclick,moveup + "" + builditemlist);
Now, let's analyze the two parameters you sent to the Builditemlist function. The first parameter corresponds to the ID of the generated control (the <select> label). The second parameter is another ID, consistent with the previous one, but preceded by a "__". This is one that you still need to add to your Web control's hidden text box, which will act as a placeholder for the list of "serialized" items. I want to register this hidden text field in the OnPreRender event.

protected override void OnPreRender (EventArgs e)
{
Base. OnPreRender (e);
if (Page!= null)
{
Page.ClientScript.RegisterHiddenField ("__" + This.id, "");
}
}

Notice that I have used the ID of our control to identify the hidden text field.

So far, you've got a fully functional Web control, where client JavaScript is bound to two buttons. The JavaScript succeeds in reordering the items in the listbox and serializing their contents into a string; The string is then stored in a hidden text field. All of these occur on the client. If a postback occurs, no reordering occurs because the item server property of the control does not receive any changes you made to it when it is reordered, but fortunately, this change occurred in a serialized snapshot of the form in the hidden text field. Now you have the content that you can use with the Item property. So, next, how do you do that?

   Second, synchronization

To achieve synchronization in the first postback and all subsequent postbacks, ASP. NET provides a LoadPostData method in the implementation of IPostBackDataHandler interface. Call this loadpostdata method every time you send it back, so you need to do some work here.

It is worth mentioning that ASP.net 2.0 has trimmed a small place that has been overlooked in version 1.1, but this modification can make your job much easier. The ASP.net ListBox control has implemented the IPostBackDataHandler interface in two versions (1.1 and 2.0). But in version 2.0, Microsoft makes this interface's approach to define virtualization (virtual, called Overridable in VB). This means that you do not have to implement this interface in the Enhancedlistbox control; instead, you only need to overload the LoadPostData method.

More importantly, it also means that you can access the base class implementation without having to create all the functionality that already exists in your extended control. What's the function? This includes everything Microsoft has added: To work with item collections, Selectedindex,selectedvalue and SelectedItem properties, and many other code that performs the function of the ListBox control. In ASP.net 1.1, you must implement this interface in your derived control and provide your own definition code for both methods, including not only your own code but also what Microsoft has achieved in its control.

I suspect that someone in Microsoft has discovered the error in their implementation and turned the method into virtual so that developers can access the base class code. So, in Source listing 6, show you how to implement the overloaded LoadPostData method. In this overload, you will first invoke the base class implementation code, and then add the code you need to synchronize with the item collection.

Alternatively, you can take advantage of the ListBox control-by writing it into a composite control. At this point, you need to map each attribute in the listbox to your enhancedlistbox so that it becomes a drop-point character for the ListBox control. Either way, or by recreating the LoadPostData method, you still need to write a lot of code. If I write this control specifically for asp.net1.1, then I'm likely to take the most straightforward scenario: a composite control scenario.

The LoadPostData method enables you to access each domain that is sent to the server, including your hidden text field (stored in the postcollection parameter to be passed to this method). You can ask: Why do I need the hidden text field instead of using this parameter to access the returned <select> element? Now, let me explain. First, look back at the typical ASP era when you used the Request.Form attribute to access page fields. At the time of the postback, the only part of the <select> element that you can access is the selected item. In this scenario, you need a complete list of contents (therefore, including hidden text fields). Listing 6 shows you how to parse the contents of the Hidden text field and add the item back to the item collection. Notice how you invoke the base class implementation.

Finally, when you first build the control, you must build the hidden text field in case the page is sent back before any reordering occurs. The last line of the Render method is:

Output. Write ("<script language= ' JavaScript ' >builditemlist (document.all." + this.) ClientID + ", document.all.__" + this. ClientID + "); </script>");
You can see this at the end of Listing 1.

You can now use the Enhancedlistbox control to reorder items, post back, and make sure that the server store for the control is fully synchronized with the client store that was changed at the client before the page is rebuilt. So now let's use the same technique to build a composite control listmover.

  III. Building composite Controls-listmover

The Listmover control contains two Enhancedlistbox controls, and some buttons are used to move items back and forth between the two lists. Using these composite controls to build technology, you can learn how to create child controls and use some HTML to build them, and the final control looks like Figure 2. For this control, you need to be aware of where certain things must occur.


Figure 2. This listmover control provides a standard way for users to move items between two lists.


First, with the same technology as in previous controls, you must add the JavaScript code needed in this control to the overloaded version of the OnInit event. Listing 7 shows the JavaScript code you need. As you did in the previous control, you also use JavaScript to access elements in a listbox (the <select> Element). Also, I've compiled functions to add items to a list, delete items from a list, and add or remove all items from a list.

Instead of creating a single "move" method, I've made it possible to implement property based settings that make it optional to delete items from a list. There's no doubt that this will make the final controls stronger, but I'm not going to parse the code in this article. It should also be noted that, as in the previous controls, I have also added a builditemlist method.

Now, you need to attach this client code to the button in the composite control. You can do this at the end of the CreateChildControls method and, at this point, complete the initialization of the child control and build the control collection. Here, I'll just show you the code corresponding to a button (another button code similar to this, omitted).

String s_addtoleft = "Addselecteditemtolist (document.all." +
This.lstItemsOnRight.ClientID + ", document.all."
+ This.lstItemsOnLeft.ClientID + "," +
(This. Allowduplicatesonleft? "True": "false") + ";";
String s_removefromright = "Removeselecteditemfromlist (document.all." +
This.lstItemsOnRight.ClientID + ");";
String s_builditemlist = "Builditemlist (document.all." +
This.lstItemsOnRight.ClientID + ", document.all.__" + Lstitemsonright.clientid + ");" + "builditemlist (document.all." + t His.lstItemsOnLeft.ClientID + ", document.all.__"
+ Lstitemsonleft.clientid + ");";
THIS.BTNADD.ATTRIBUTES.ADD ("onclick", S_addtoleft
+ "" + S_removefromright + "" + s_builditemlist
+ "return false");
Notice that I implemented the same work in the previous controls. I built JavaScript function calls into a string and attached them to a button. The main difference is that since this is a composite control that contains other controls, you might use the Attributes.Add method of adding code to the OnClick event, which contrasts with the way you put it on a stack in a build control. Also note that I put more than one feature in the onclick attribute, and that the function call returns false so that any postback that the button will perform is canceled.

Finally, the code initializes the call to the client function Builditemlist in a method that render overloads. This looks like the one I introduced to you in the Enhancedlistbox control, which I don't repeat here. Note that in this control, I register two hidden text fields, each corresponding to a listbox.

protected override void OnPreRender (EventArgs e)
{
Base. OnPreRender (e);
if (Page!= null)
{
Page.ClientScript.RegisterHiddenField ("__" + This.lstItemsOnRight.ClientID,
"");
Page.ClientScript.RegisterHiddenField ("__" + This.lstItemsOnLeft.ClientID,
"");
Page.registerrequirespostback (this);
}
}
Now that you have built the composite control, you can provide some client JavaScript and bind it to the button. As before, you can put it on a form and use it; however, before you add synchronization code, it will still encounter the problem you encountered in the first control-you can move items back and forth, but once you initialize a postback (through any other control on the form), The control reverts to its state before it was sent back.

To modify this problem, you need to implement the same work you did in the first control. However, now that you are developing a composite control rather than extending an already existing control, you need to implement the IPostBackDataHandler interface and provide the implementation code for the LoadPostData and RaisePostDataChangedEvent methods. These implementations (see listing 7) are basically consistent with the previous controls, except that you want to implement synchronization of the item collections in two Enhancedlistbox controls rather than just one control. And as before, you need to make sure that you save your selectedindex position, so that you can set it back after you have synchronized the set of items. Also note that in the first control, you overload the LoadPostData method of the base control, so that its base class is called somewhere. Now that you're writing a composite control from scratch, there's no base class to call and just provide your own method implementation.

The final version of this control contains several new properties: including properties that determine whether items added to a list can be removed from another list (if a list will allow duplicates); It also includes extensible styling for maximum reuse purposes, and so on.

That's it. You have used a hidden text field in client script to store the state of the list box. During the postback, you use the contents of the Hidden text field to resynchronize with the server-side item collection. The end result is a nice composite control-allowing you to move back and forth between the list items without a server postback, and still be able to keep that change when a postback really happens.

  Four, take the best of both

One of the details I didn't mention earlier is why I mixed two controls in this article. In the beginning, I first showed you an enhanced version of the standard ListBox control, and then applied the two instances of the enhanced control to the Listmover control instead of using two standard ListBox controls to build this listmover. In this article, I don't cover the Properties section of the Listmover control, which is responsible for mapping the properties that are added to the Enhancedlistbox control. In this way, I can control the enhancements of two Enhancedlistbox controls from a Listmover control that contains two Enhancedlistbox controls. So you can see that you have the best feature that combines two controls-you have a Listmover control that allows you to move and reorder items between two lists or individual lists.

In fact, the real key here is asp.net development--full encapsulation--for Web controls. The Enhancedlistbox control in this article contains all the code that implements its goal, which is to reorder its items. When I include two of these controls in a Listmover control, I can use all the intelligence that accompanies them as an additional feature of the new control, including the client script that each control contains and the synchronization capabilities of the client to the server in the Enhancedlistbox control. Therefore, this listmover control only needs to pay attention to its own function. Figure 3 shows the Listmover control with the Enhancedlistbox control, where the Reorder button is open.


Figure 3. By combining Listmover and Enchancedlistbox controls, you provide users with a complete control of two lists so that you can move between items in one list or two lists.


Finally, I strongly encourage you to download this article complete the source code for research. Now that I've written these controls, I've used listmover many times, and the Enhancedlistbox control can almost replace the standard ASP.net listbox control in all my engineering developments.

   v. Summary

I've shown you in this article how to keep the synchronization between the server and the client within a Web control, and the techniques used here can be applied to many similar situations. Although ASP.net 2.0 introduces an intuitive interface for handling script callbacks, making the feature fully located on the client is one of the fastest solutions and can be compatible with ASP.net 1.1. To be honest, I'm more interested in the callback capabilities built into the ASP.net 2.0, so please study it together.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.