Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 15 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
15
Dung lượng
406,48 KB
Nội dung
txtTitle_TextChanged event and will update Session state with the latest value. Now when you move to another page and return, this page will have your changed value instead of saying “Title.” You can now launch the page in your browser to test its behavior. What You Have Learned MagicAjax is a framework that will make any .NET developer feel comfortable. The panel, changed- HTML-type architecture makes creating Ajax applications easy because the framework is responsible for creating the wireup between the browser and the server. In fact, the only custom JavaScript you wrote in these examples was to update style sheet settings and not to facilitate Ajax scripting. MagicAjax also provides hooks for you to call code written in your code-behind that is not a part of the traditional ASP.NET Event Postback pattern. Anthem.NET URL: http://anthem-dot-net.sourceforge.net Although the Anthem.NET framework features panels and a changed HTML architecture, you also have the option of using custom controls and returning data structures to the client. Anthem.NET is architected to use page Register directives instead of forcing you to inherit from a base class, and you are not required to implement preprocessing to harness its power. Anthem.NET truly represents the best of both worlds. Setup Before you begin using Anthem.NET, you must first download the files and then reference them in a web project. The following steps help you build a solution that houses all the samples you create for the Anthem.NET. Downloading Files 1. If you haven’t done so yet, download the zip file containing the Anthem.NET DLL from http://beginningajax.com/downloads/chapter9/Chapter9-Framework DLLs.zip. 2. Extract the files, and place them in a convenient location. Creating the Solution 1. Open Visual Studio 2005. 2. Click File➪New➪Website. 3. Select the ASP.NET Website template. 4. Choose File System under location. 5. Set the path to c:\BeginningAJAX\Chapter9\AnthemDemo. 6. Choose C# as the language. 7. Click OK. 231 Other Ajax Frameworks for .NET 12_78544X ch09.qxp 7/18/06 3:16 PM Page 231 Referencing ComfortASP.NET 1. In the Solution Explorer, right-click on the project name and select Add ASP.NET Folder. 2. Choose App_LocalResources to create the ASP.NET folder. 3. Copy Anthem.dll (from the zip file you extracted) to the App_LocalResource folder. 4. Create a reference to the Anthem.dll. Copying the Data File 1. Copy the Resources.xml you created in the last section into the App_Data folder in the solution. Using Anthem.NET Since you have had an opportunity to use panels, the coming examples will focus on using Anthem.NET’s custom controls. You will also have an opportunity to work with a data structure returned from the server. Working with Anthem.NET’s data structures will seem familiar to you because the process is nearly identical to the way you would do it using the Ajax.NET framework. Example 1: Hello World Anthem.NET’s introductory example will follow the same pattern as the examples for ComfortASP.NET and MagicAjax. This demonstration will use Anthem.NET controls. The Anthem button and label inherit from the stan- dard .NET controls and extend them for the framework. While the markup for the controls remains the same in this example, you will set a property in the code-behind that will flag the label control for Anthem.NET to use for updating instead of the traditional .NET postback mechanism. Figure 9-12 shows an example of how the page will look when you are done. Try It Out Implementing “Hello World” Begin by adding a web form to the solution and naming it HelloWorld.aspx. Now add the Anthem register directive to the page just under the <%@ Page %> directive. <%@ Register TagPrefix=”anthem” Namespace=”Anthem” Assembly=”Anthem” %> Next, update the markup by adding the following code between the <div> tags. <anthem:Button ID=”Button1” OnClick=”Button1_Click” Text=”Test” runat=”server” /> <anthem:Label ID=”Label1” runat=”server” /> 232 Chapter 9 12_78544X ch09.qxp 7/18/06 3:16 PM Page 232 Finally, update the HelloWorld class with the following code-behind. public partial class HelloWorld : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void Button1_Click(object sender, EventArgs e) { this.Label1.Text = “Hello World “ + DateTime.Now.ToString(); this.Label1.UpdateAfterCallBack = true; } } When you click on the Test button, the label will update with the text “Hello World” and the current date and time. Click the button multiple times to see that the time will continue to be updated without a postback to the server. You may now test the behavior by launching the page in the browser. Figure 9-12 233 Other Ajax Frameworks for .NET 12_78544X ch09.qxp 7/18/06 3:16 PM Page 233 Example 2: Complex Controls Just as you observed with ComfortASP.NET, the framework operates well with a single textbox, but how will the system perform with more demanding controls? This example will guide you through adding a GridView control to the page and will use Anthem.NET to respond to the SelectedIndexChanged method. Figure 9-13 is an example of the way the page will look when you are done. Figure 9-13 Try It Out Using Complex Controls Begin by adding a new web form to the solution, naming it ComplexControls.aspx. Now add the Anthem register directive to the page just under the <%@ Page %> directive. <%@ Register TagPrefix=”anthem” Namespace=”Anthem” Assembly=”Anthem” %> Next, update the markup by adding the following code between the <div> tags: <anthem:Button ID=”btnLoadResources” OnClick=”btnLoadResources_Click” Text=”Load Resources” runat=”server” /> 234 Chapter 9 12_78544X ch09.qxp 7/18/06 3:16 PM Page 234 <anthem:gridview id=”grdResources” runat=”server” OnSelectedIndexChanged=”grdResources_SelectedIndexChanged”> <Columns> <asp:CommandField ShowSelectButton=”True” /> </Columns> </anthem:gridview> <p>Selected index: <anthem:Label ID=”lblSelectedIndex” runat=”server” /></p> Finally, switch to the code view, and add the following code to the ComplexControls class: public partial class ComplexControls : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void btnLoadResources_Click(object sender, EventArgs e) { DataSet ds; ds = new DataSet(); ds.ReadXml(Server.MapPath(“~/App_Data/Resources.xml”)); this.grdResources.DataSource = ds; this.grdResources.DataBind(); this.grdResources.UpdateAfterCallBack = true; } protected void grdResources_SelectedIndexChanged(object sender, EventArgs e) { this.lblSelectedIndex.Text = this.grdResources.SelectedIndex.ToString(); this.lblSelectedIndex.UpdateAfterCallBack = true; } } When you click the Load Resources button, the grid is loaded with data from the XML store. When you click on a Select link in the grid, the text of the label is updated with the selected index value. You can now test the behavior by launching the page in the browser. Example 3: Custom Attributes When Anthem.NET extends web controls, part of the new interface includes some attributes you can define to make working with the controls easier. In some frameworks, you must manually script a fea- ture to disable a button when a call to the server is initiated. With an Anthem button, you may set an attribute that implements this feature for you automatically. You may also find that you want to change the text of a button once the page begins to contact the server. Again, Anthem.NET’s button control allows you to declaratively define this behavior. 235 Other Ajax Frameworks for .NET 12_78544X ch09.qxp 7/18/06 3:16 PM Page 235 Figure 9-14 shows an example of how the page will look after you click the button defined with Anthem.NET’s custom attributes. Figure 9-14 Try It Out Using Custom Attributes Begin by adding a new web form to the solution naming it CustomAttributes.aspx. Now add the Anthem register directive to the page just under the <%@ Page %> directive. <%@ Register TagPrefix=”anthem” Namespace=”Anthem” Assembly=”Anthem” %> Next, update the markup by adding the following code between the <div> tags: <anthem:Button ID=”btnTest” EnabledDuringCallBack=”false” TextDuringCallBack=”Working ” Text=”Test” runat=”server” OnClick=”btnTest_Click” /> <anthem:Label ID=”lblTest” runat=”server” /> 236 Chapter 9 12_78544X ch09.qxp 7/18/06 3:16 PM Page 236 Finally, update the CustomAttributes class with the following code-behind: public partial class CustomAttributes : System.Web.UI.Page { protected void btnTest_Click(object sender, EventArgs e) { System.Threading.Thread.Sleep(5000); this.lblTest.Text = DateTime.Now.ToString(); this.lblTest.UpdateAfterCallBack = true; } } When you click the Test button, the server will hesitate for 5 seconds before returning a response to the browser. During this delay, you may observe that the button is disabled and the text is changed to “Working ” When the browser regains control of the operation the button is enabled and the text returns to its original value. Now test the behavior by launching the page in the browser. Example 4: Client Functions In addition to custom attributes, Anthem.NET exposes client-side events. These events give you a high degree of control over your page when contacting the server. This example will show you how to implement some custom logic before the framework is contacted, before callback begins, and when the callback is completed. When you are wiring up code-behind events on an ASP.NET page, the OnClick attribute will link the client-side click event to the ASP.NET postback mechanism to contact the code on the server to run the click event method defined in your code-behind. Anthem.NET implements an OnClientClick attribute where you may define a function name to run after the button is clicked but before the Anthem.NET framework is invoked. The PreCallBackFunction will fire as Anthem.NET takes control of the request but before contacting the server. Finally, the PostCallBackFunction will define a JavaScript function that is run once a response is recognized by the browser. Notice in the example that each JavaScript function is defined passing an argument of this to the method. Passing the argument will expose a reference to the initiating control, in this case the Test but- ton. This approach is valuable as you now have an easy way to access the control that originated the request without having to parse the DOM. Figure 9-15 is an example of the way the page will look when you first click on a button using client functions. 237 Other Ajax Frameworks for .NET 12_78544X ch09.qxp 7/18/06 3:16 PM Page 237 Figure 9-15 Try It Out Using Client Functions Begin by adding a new web form to the solution, naming it ClientFunctions.aspx. Now add the Anthem register directive to the page just under the <%@ Page %> directive: <%@ Register TagPrefix=”anthem” Namespace=”Anthem” Assembly=”Anthem” %> Next, add the following code within the <head> tag: <script type=”text/javascript”> function btnTest_PreCallBack() { alert(“This happens before contacting the server”); } function btnTest_PostCallBack() { alert(“This happens after getting a “ + “response from the server”); } function btnTest_Click(control) { alert(“This happens right after you click the ‘“ + 238 Chapter 9 12_78544X ch09.qxp 7/18/06 3:16 PM Page 238 control.value + “‘ button.”); } </script> Each method will alert the browser of which event is firing. The btnTest_Click function will access the originating control’s properties to build its statement. Next, update the markup by adding the following code between the <div> tags: <anthem:Button ID=”btnTest” OnClientClick=”btnTest_Click(this)” PreCallBackFunction=”btnTest_PreCallBack(this)” PostCallBackFunction=”btnTest_PostCallBack(this)” Text=”Test” OnClick=”btnTest_Click” runat=”server” /> <anthem:Label ID=”lblTest” runat=”server” /> Finally, update the ClientFunctions class with the following code-behind: public partial class ClientFunctions : System.Web.UI.Page { protected void btnTest_Click(object sender, EventArgs e) { this.lblTest.Text = DateTime.Now.ToString(); this.lblTest.UpdateAfterCallBack = true; } } When you click the button, each event will fire the appropriate JavaScript function. You can now test the behavior by launching the page in the browser. Example 5: Invoke Page Method This example demonstrates how you can use Anthem.NET to call sever-side code without requiring the use of a panel or custom controls. Anthem.NET implements this feature in a similar fashion to the Ajax.NET framework, but instead of creating a proxy object for each page that exposes a method to the client, Anthem.NET has a single function that will take care of communicating with the server. Anthem.NET’s function for interfacing with the code-behind is called Anthem_InvokePageMethod. This function may take three arguments. ❑ The first argument is the name of the method on the server you want the function to execute. ❑ The second argument is an array of the server-side method argument values. ❑ Lastly, the third argument is for the callback function and is the name of the function that the browser will call when the server has completed its processing. The callback function argument is optional. 239 Other Ajax Frameworks for .NET 12_78544X ch09.qxp 7/18/06 3:16 PM Page 239 Figure 9-16 is an example of the way the page will look when you are done. Figure 9-16 Try It Out Invoking Page Method Begin by adding a new web form to the solution, naming it InvokePageMethod.aspx. Now add the fol- lowing code within the <head> tag: <script type=”text/javascript”> function Multiply() { var int1; var int2; int1 = document.getElementById(‘txtInt1’).value; int2 = document.getElementById(‘txtInt2’).value; Anthem_InvokePageMethod(‘Multiply’,[int1, int2],Multiply_CallBack); } function Multiply_CallBack(result) { document.getElementById(‘txtResult’).value = result.value; } </script> 240 Chapter 9 12_78544X ch09.qxp 7/18/06 3:16 PM Page 240 [...]... pattern here is the same as with Ajax. NET First, you must register the page with the Anthem.NET framework Then you add the Anthem.Method attribute to your method As stated above, the Multiply method requires two factors as arguments and returns the product Now test the behavior by launching the page in the browser Example 6: Direct Scripting (Micro-Content) Recall from the MagicAjax section how you implemented... InvokePageMethod class with the following code-behind: public partial class InvokePageMethod : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Anthem.Manager.Register(this); } [Anthem.Method] public int Multiply(int int1, int int2) { return (int1 * int2); } } 241 Chapter 9 The code defined here should immediately be familiar to you from your experience with Ajax. NET The pattern... directive Next, add the following code within the tag: input { border:solid 1px #fff; } focus { background-color:#eee; border:dashed 1px #ccc; } blur { 242 Other Ajax Frameworks for NET background-color:#fff; border:solid 1px #fff; } mouseOver { border:solid 1px #c00; } mouseOut { border:solid... object, you may then decide what to do on the client with the error The response object returned by Anthem.NET includes an error object in its interface If the error property is not null, then you have encountered an error on the server Figure 9-17 shows an example of how the page will appear when Anthem wraps up an unhandled server exception 244 Other Ajax Frameworks for NET Figure 9-17 Try It Out Handling... { border:solid 1px #fff; } The style sheet entries hold the formatting information to give signals to the user as to what is happening (This is the exact same CSS you implemented in the MagicAjax section, so if you have the code available you can copy it into your file for this example.) Next, add the following JavaScript just after the style sheet definitions ... markup by adding the following code between the tags: Finally, update the DirectScripting class with the following code-behind: public partial class DirectScripting : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!this.Page.IsPostBack) { this.txtTitle.Attributes.Add(“onfocus”,... txtTitle_TextChanged(object sender, EventArgs e) { this.Session.Add(“title”,this.txtTitle.Text); this.txtTitle.AutoUpdateAfterCallBack = true; } } Although much of this implementation is similar to the MagicAjax demonstration, notice the different approaches Using Anthem.NET you declare an Anthem TextBox control and use the built-in mechanism of firing the TextChanged event to initiate a request to the server... You can now test the behavior by launching the page in the browser Example 7: Server Exceptions A feature exclusive to Anthem.NET from all the frameworks listed in this section is the ability to deal with unhandled server-side exceptions In other frameworks, should your application encounter an unhandled exception, the error may bubble up to the user interface as the cryptic and intimidating stock...Other Ajax Frameworks for NET The block of JavaScript is responsible for gathering the user input and passing it to the Anthem_Invoke PageMethod function The first argument in this function is the name of the... exception 244 Other Ajax Frameworks for NET Figure 9-17 Try It Out Handling Server Exceptions Begin by adding a new web form to the solution, naming it ServerException.aspx Next, add the following code within the tag: function ShowError() { Anthem_InvokePageMethod(‘ShowError’,null,ShowError_CallBack); } function ShowError_CallBack(response) { if(response.error != . Select the ASP. NET Website template. 4. Choose File System under location. 5. Set the path to c:BeginningAJAXChapter9AnthemDemo. 6. Choose C# as the language. 7. Click OK. 231 Other Ajax Frameworks. 9-12 233 Other Ajax Frameworks for .NET 12_78544X ch09.qxp 7/18/06 3:16 PM Page 233 Example 2: Complex Controls Just as you observed with ComfortASP.NET, the framework operates well with a single. Page 231 Referencing ComfortASP.NET 1. In the Solution Explorer, right-click on the project name and select Add ASP. NET Folder. 2. Choose App_LocalResources to create the ASP. NET folder. 3. Copy