YOMEDIA
ADSENSE
Beginning Ajax with ASP.NET- P18
72
lượt xem 7
download
lượt xem 7
download
Download
Vui lòng tải xuống để xem tài liệu đầy đủ
Beginning Ajax with ASP.NET- P18:Thank you for purchasing Beginning Ajax with ASP.NET. We know that you have a lot of options when selecting a programming book and are glad that you have chosen ours. We’re sure you will be pleased with the relevant content and high quality you have come to expect from the Wrox Press line of books.
AMBIENT/
Chủ đề:
Bình luận(0) Đăng nhập để gửi bình luận!
Nội dung Text: Beginning Ajax with ASP.NET- P18
- Other Ajax Frameworks for .NET 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
- Chapter 9 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 directive. Next, update the markup by adding the following code between the tags. 232
- Other Ajax Frameworks for .NET 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
- Chapter 9 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 directive. Next, update the markup by adding the following code between the tags: 234
- Other Ajax Frameworks for .NET Selected index: 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
- Chapter 9 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 directive. Next, update the markup by adding the following code between the tags: 236
- Other Ajax Frameworks for .NET 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
- Chapter 9 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 directive: Next, add the following code within the tag: 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
- Other Ajax Frameworks for .NET control.value + “‘ button.”); } 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 tags: 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
- Chapter 9 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 tag: 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; } 240
- 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 method on the server that you want to execute. In an upcoming code block, you will define a method on the page named Multiply, which is the code this function will execute. The next argument is an array of values that represent the sig- nature of the Multiply method on the server. Multiply requires two integers to multiply together and returns the result. The final argument is the address of the callback function. After Multiply_CallBack runs, the textbox txtResult’s value will contain the product of the two numbers. You will not add the Anthem page directive to the page in this example. The technique used here will use Anthem.NET’s functionality to access methods in the code-behind directly from JavaScript. This approach does not require that you use Anthem.NET controls. Next, update the markup by adding the following code between the tags: X The HTML you see here is a bit different from the type of markup you have defined in the previous examples. In this case, you are not using a panel, nor are you declaring your controls as custom controls. This approach uses JavaScript to directly access the code-behind methods. Each input box is a standard HTML input box, and the work begins when you click the Multiply button. Finally, update the 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 here is the same as with Ajax.NET. First, you must register the page with the Anthem.NET frame- work. 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 the micro-content pattern. You will now implement the same pattern using Anthem.NET. This exercise uses Anthem.NET as well as some custom Cascading Style Sheet definitions to power the change in the user interface to give clues as to what is happening. The page will provide initial clues that parts of the page are editable by drawing a border over the text when the cursor hovers over the editable area. (You can refer back to Figure 9-10 to remind yourself of what this looks like.) The next clue is to change the appearance of the control when the user has placed this area of the page in “edit mode.” (Refer back to Figure 9-11 to see an example of this.) Finally when the focus is lost from the control Anthem.NET will contact the server and allow the back-end processing to persist the latest data. Under normal circumstances you would probably persist the data to a data store of some kind. For demonstration purposes, this exercise will simply store the information in Session state. This way, once you make a change to the data, you can navigate off the page and return to see your latest changes, but you avoid having to implement a data layer just for this example. Try It Out Using Direct Scripting Begin by adding a new web form to the solution, naming it DirectScripting.aspx. Now add the Anthem register directive to the page just under the 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 1px #fff; } The style sheet entries hold the formatting information to give signals to the user as to what is happen- ing. (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. function ChangeCSSClass(element,className) { element.className = className; } Next, update the 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”, “ChangeCSSClass(this,’focus’);”); this.txtTitle.Attributes.Add(“onblur”, “ChangeCSSClass(this,’blur’);”); this.txtTitle.Attributes.Add(“onmouseover”, “ChangeCSSClass(this,’mouseOver’);”); 243
- Chapter 9 this.txtTitle.Attributes.Add(“onmouseout”, “ChangeCSSClass(this,’mouseOut’);”); if (this.Session[“title”] != null) { this.txtTitle.Text = this.Session[“title”].ToString(); } } } protected void 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 mecha- nism of firing the TextChanged event to initiate a request to the server. Once the server is contacted, you can apply the Session value and set the AutoUpdateAfterCallBack property on the TextBox control equal to true. 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 yellow and white ASP.NET error page. While the subject of structured exception management is out of the scope of this book, you will implement an example that will enforce this foundational rule: protect the user from useless error messages. Anthem.NET will wrap up unhandled exceptions into a JSON error object. When you encounter this 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 Server Exceptions Begin by adding a new web form to the solution, naming it ServerException.aspx. Next, add the fol- lowing code within the tag: function ShowError() { Anthem_InvokePageMethod(‘ShowError’,null,ShowError_CallBack); } function ShowError_CallBack(response) { if(response.error != null) { alert(response.error); } else { alert(“No errors here, just keep on working!”); } } 245
ADSENSE
CÓ THỂ BẠN MUỐN DOWNLOAD
Thêm tài liệu vào bộ sưu tập có sẵn:
Báo xấu
LAVA
AANETWORK
TRỢ GIÚP
HỖ TRỢ KHÁCH HÀNG
Chịu trách nhiệm nội dung:
Nguyễn Công Hà - Giám đốc Công ty TNHH TÀI LIỆU TRỰC TUYẾN VI NA
LIÊN HỆ
Địa chỉ: P402, 54A Nơ Trang Long, Phường 14, Q.Bình Thạnh, TP.HCM
Hotline: 093 303 0098
Email: support@tailieu.vn