Lập trình .net 4.0 và visual studio 2010 part 40 doc

9 211 0
Lập trình .net 4.0 và visual studio 2010 part 40 doc

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

Thông tin tài liệu

CHAPTER 11  MICROSOFT AJAX LIBRARY 262 Binding to External Services Of course, when you are binding to data, you usually want to retrieve it from an external source. The DataView control allows you to very easily accomplish this and bind to many different types of services, for example: • ASMX web service • WCF web services • WCF Data Services • ASP.NET MVC controller actions • JSONP service • Basically anything that returns JSON-formatted data You will now use client templates to bind to both an ASMX and WCF web service. WebService (.asmx) First the web service: 1. Add a new class called Person to the project and enter the following class definition: public class Person { public string Name { get; set; } public string Age { get; set; } } 2. Add a new .asmx web service to the project called GetData.asmx. 3. Add the following using directive to GetData.asmx.cs: using System.Web.Script.Services; 4. Uncomment the following attribute in the GetData class: [System.Web.Script.Services.ScriptService] 5. Now create a new method to return a list of people. Note the call to System.Threading.Sleep(); it slows down the service so you can see the results appear (you might want to remove the sys- template style to see the effect latency can have): [WebMethod] [System.Web.Script.Services.ScriptMethod] public List<Person> GetPeople() { System.Threading.Thread.Sleep(2000); List<Person> People = new List<Person>(); People.Add(new Person { Name = "Alex Mackey", Age = "28" }); People.Add(new Person { Name = "Matt Lacey", Age = "31" }); People.Add(new Person { Name = "Barry Dorrans", Age = "78" }); CHAPTER 11  MICROSOFT AJAX LIBRARY 263 People.Add(new Person { Name = "Craig Murphy", Age = "33" }); People.Add(new Person { Name = "Chris Hay", Age = "32" }); People.Add(new Person { Name = "Andy Gibson", Age = "21" }); return People; } 6. Copy the file dataviewProgrammatic.htm and rename the new copy as dataviewAsmx.htm. 7. Replace the existing script block with the following code: <script type="text/javascript"> Sys.require([Sys.components.dataView, Sys.scripts.WebServices], function () { Sys.create.dataView('#peopleView', { dataProvider: "GetData.asmx", fetchOperation: "GetPeople", autoFetch: "true" }); }); </script> 8. Right-click dataviewAsmx.htm and select View in Browser. After about two seconds, you should see the results of the web service bound to the template. WCF Binding Binding to a WCF service is accomplished in a very similar way. In this example, you will pass in a name parameter as well as retrieve a single person. 1. Add a new AJAX-enabled WCF service (similar to standard WCF service, but has some additional attributes to enable JavaScript methods calls) to the project called GetDataFromWCF.svc. 2. Now add the following method to the new web service: [OperationContract] public Person GetPerson(string Name) { //System.Threading.Thread.Sleep(2000); List<Person> People = new List<Person>(); People.Add(new Person { Name = "Alex Mackey", Age = "28" }); People.Add(new Person { Name = "Matt Lacey", Age = "31" }); People.Add(new Person { Name = "Barry Dorrans", Age = "78" }); People.Add(new Person { Name = "Craig Murphy", Age = "33" }); People.Add(new Person { Name = "Chris Hay", Age = "32" }); People.Add(new Person { Name = "Andy Gibson", Age = "21" }); return People.FirstOrDefault(p => p.Name == Name); } CHAPTER 11  MICROSOFT AJAX LIBRARY 264 3. Replace the current script block in webserviceWCF.htm with the following code: <script type="text/javascript"> //We need Sys.scripts.WebServices in order to interact with the WCF service Sys.require([Sys.components.dataView, Sys.scripts.WebServices], function () { Sys.create.dataView('#peopleView', { dataProvider: "GetDataFromWCF.svc", fetchOperation: "GetPerson", fetchParameters: { Name: "Alex Mackey" }, autoFetch: "true" }); }); </script> JSONP The latest release of the AJAX libraries contains support for working with JSONP services. JSONP (or JSON with padding) is a bit of a hack that allows you to make AJAX calls to external domains (not allowed with standard XHTTP requests and utilized by Flickr and Bing). JSONP works by exploiting the fact that you can reference a script file on a different server. This script then calls a function in the calling page to return the data. DataView contains support for binding to JSONP services such as those offered by Flickr and Bing. The Microsoft AJAX site has an example of how to call a JSONP service at http://www.asp.net/ ajaxlibrary/HOW%20TO%20Use%20JSONP%20to%20Request%20Data%20from%20Remote%20Websites.ashx. For more information on JSONP, please refer to the following links: • http://ajaxian.com/archives/jsonp-json-with-padding • http://www.west-wind.com/Weblog/posts/107136.aspx Advanced Binding Hopefully, by now you are excited about how easy the Microsoft AJAX libraries can make client-side data binding. The ASP.NET AJAX libraries also contain a number of other useful features that you will look at now: • Conditional rendering • Converters • Two-way data binding, • Implementation of the observer pattern CHAPTER 11  MICROSOFT AJAX LIBRARY 265 Conditional Rendering Sometimes you will want to apply logic to the rendering of your contentperhaps in a medical application to highlight abnormal lab results. The Microsoft AJAX libraries allow you to do this by embedding conditional logic within your markup.  CAUTION Be careful when using this approach. You are polluting the UI with business logic, which will be harder to maintain and is more easily corrupted by designers. Let’s look at the different conditional logic statements you can utilize. sys:if The sys:if condition applies only if a condition is true. Suppose that you want to render a warning div if a particular person’s name comes up in the bound data. This is easily achieved as follows: <div sys:if="$dataItem.Name == 'Barry Dorrans'">Warning do not approach!</div> $dataItem In the preceding example, you needed to reference data in the bound set. To do this, you used the $dataItem object. This allows you to access individual properties with the following syntax: $dataItem.MyPropertyName $index You can also apply code based on the index position of the item by querying the $index pseudo property: <div sys:if="$index == 0">first</div> sys:codebefore and sys:codeafter Sometimes you want to render HTML before or after the element you are binding. The codebefore and codeafter statements allow you to do this: <div sys:if="$index == 0" sys:codebefore="$element.innerHTML='I get placed first'" sys:codeafter="$element.innerHTML='I get placed second'" > </div> CHAPTER 11  MICROSOFT AJAX LIBRARY 266 sys:innertext and sys:innerhtml Finally it can be useful to output text or HTML (similar to JavaScript’s innerText or innerHtml properties): <div sys:innertext=”{{ foo }}”></div> <div sys:innerhtml=”{{ foo }}”></div> Binding Converters When you bind data you might want to perform some processing on a value before rendering it. For example, maybe you don’t need the level of precision the data has, or you want to convert it to a different measurement or format it to the user’s current locale. This can be accomplished with a converter that is simply a standard JavaScript function. This example creates a function to uppercase a string: function ToUpper(Input) { return Input.toUpperCase(); } This function can then be used in binding like so: <div class=""> {binding Name, convert=ToUpper} </div> Two-way Binding Until now, you have bound items using one-way binding. One-way binding is used automatically when you declare your binding using two curly brackets, one on each side of the data item: {{ Name }} ASP.NET AJAX also allows you to implement two-way data bindingif an item is updated, any other page elements bound to the same data item will also be updated. You will also soon learn how to bind to a WCF service and persist changes back. To use two-way binding, simply use one curly bracket instead of two when you define the template: {binding Name} If you want to be more verbose/explicit about your intentions you can also specify the binding mode: {binding Name mode=oneWay} or {binding Name mode=twoWay} CHAPTER 11  MICROSOFT AJAX LIBRARY 267 Let’s take a look at this in action now: 1. Copy the file dataviewProgrammatic.htm and rename the new file as dataviewTwoWay.htm. 2. Modify the template tag to the following: <body> <div id="peopleView" class="sys-template"> <div class="dataItem"> <input type="text" sys:value="{binding Name}" /> <input type="text" sys:value="{binding Name}" /> <hr /> </div> </div> </body> 3. Now run the application, edit one of the text boxes, and tab out of it, noting that the new value is updated automatically (see Figure 11-2). Figure 11-2. Two-way data binding CHAPTER 11  MICROSOFT AJAX LIBRARY 268 Sys.Observer A common problem when designing web applications is the need to refresh the UI in response to changes in an underlying data source. You might have accomplished this by polling an object or service for changes, but you now have a better option with the Sys.Observer functionality. Sys.Observer functionality is Microsoft AJAX libraries’ implementation of the popular Observer pattern. You will now write some example code to tell ASP.NET AJAX to monitor an array of numbers and refresh the template if anything changes to the array. You will then create a function that adds a random number to the array and note how the result is returned: 1. Copy and paste the file dataviewDeclarative.htm and rename the copy to observer.htm. 2. Replace the existing script block with the following code: <script type="text/javascript"> Sys.require(Sys.components.dataView); var dataArray = []; Sys.Observer.makeObservable(dataArray); function NewRandom() { var newRand = Math.random(); var newItem = { MyRandom: newRand }; dataArray.add(newItem); } </script> 3. Replace the body section with the following HTML: <div id="peopleView" class="sys-template" sys:attach="dataview" dataview:data="{{dataArray}}" > <div class="dataItem"> {{ MyRandom }} <hr /> </div> </div> Note that you make a call to the method Sys.Observer.makeObservable(dataArray) that tells ASP.NET AJAX libraries that you are interested in any changes to this object and that it needs to refresh any templates. WCF Data Services Data Context The ASP.NET AJAX libraries can be easily integrated with WCF Data Services. If you are unfamiliar with WCF Data Services, please refer to Chapter 9 for more in-depth details of how to create a service.  NOTE As described in Chapter 9, WCF Data Services used to be called ADO.NET Data Services, which is reflected in the names of the templates used in this exercise. CHAPTER 11  MICROSOFT AJAX LIBRARY 269 The steps to integrate with a data context are described as follows: 1. Add a new ADO.NET entity data model to the project called book.edmx that contains the Films table from the demo database with pluralization options switched on. 2. Now add a new ADO.NET data service called BookService. 3. Modify BookService’s InitializeService() method to the following to enable full read/write access (don’t do this in a production application): public static void InitializeService(DataServiceConfiguration config) { config.SetEntitySetAccessRule("*", EntitySetRights.All); config.SetServiceOperationAccessRule("*", ServiceOperationRights.All); config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2; } 4. Copy dataviewProgrammatic.htm and rename the new copy as dataviewAdo.htm. 5. Modify the script block to the following code: <script type="text/javascript"> var dataContext; Sys.require([Sys.components.dataView, Sys.components.adoNetDataContext], function () { dataContext = Sys.create.adoNetDataContext({ serviceUri: "BookService.svc" }); var master = Sys.create.dataView("#peopleView", { dataProvider: dataContext, fetchOperation: "Films", itemRendered: detailRendered, autoFetch: true }); function detailRendered(dataView, ctx) { Sys.bind(Sys.get("#txtFilmTitle", ctx), "value", ctx.dataItem, "Title"); } }); function SaveChanges() { dataContext.saveChanges(); } </script> CHAPTER 11  MICROSOFT AJAX LIBRARY 270 6. Finally, modify the body section to the following: <body> <input type="button" onclick="javascript:SaveChanges();" value="Save Changes" /> <div id="peopleView" class="sys-template"> <div class="dataItem"> <input id="txtFilmTitle" type="text" sys:value="title" /> <hr /> </div> </div> </body> Run the project up; you will find that the films list is bound to the DataView, and you can update the films by clicking the Save Changes button. Conclusion This release of the Microsoft AJAX libraries introduces some compelling new features that should interest all web developers. Prior to this release, I did not recommend the Microsoft AJAX libraries as a general-purpose JavaScript framework because jQuery was better documented, supported, and easier to use. However, the great news is that in this release the Microsoft AJAX libraries are integrated very nicely with jQuery. So you don’t have to make this choice anymore; you have the best of both worlds. It is worth considering what Microsoft’s motivation behind open sourcing the AJAX libraries is. Does this indicate that Microsoft is starting to pull out from its development? I’m not sure; perhaps this is unlikely given all the recent enhancements, but it is something to bear in mind. One thing for certain, however, is that there are some fantastic features in this release that should interest all web developers, whatever platform they are developing for. Further Reading • http://ajax.codeplex.com/ • http://www.asp.net/ajaxlibrary/ • http://www.jamessenior.com/ • http://weblogs.asp.net/fredriknormen/archive/2009/09/11/asp-net-ajax-4-0- preview-5-available.aspx . example of how to call a JSONP service at http://www.asp .net/ ajaxlibrary/HOW%20TO%20Use%20JSONP%20to%20Request%20Data%20from%20Remote%20Websites.ashx. For more information on JSONP, please refer. http://ajax.codeplex.com/ • http://www.asp .net/ ajaxlibrary/ • http://www.jamessenior.com/ • http://weblogs.asp .net/ fredriknormen/archive/ 200 9 /09 /11/asp -net- ajax -4- 0- preview-5-available.aspx . [System.Web.Script.Services.ScriptMethod] public List<Person> GetPeople() { System.Threading.Thread.Sleep( 200 0); List<Person> People = new List<Person>(); People.Add(new Person { Name

Ngày đăng: 01/07/2014, 21:20

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

Tài liệu liên quan