ASP NET AJAX What is AJAX Ajax which

  • Slides: 39
Download presentation
ASP. NET AJAX

ASP. NET AJAX

What is AJAX � Ajax, which stands for Asynchronous Java. Script And XML, enables

What is AJAX � Ajax, which stands for Asynchronous Java. Script And XML, enables your client-side web pages to exchange data with the server through asynchronous calls. � Probably the most popular feature driven by Ajax is the flicker-free page that enables you to perform a postback to the server without refreshing the entire page.

Ajax Frameworks � To enhance your web site with Ajax features you can choose

Ajax Frameworks � To enhance your web site with Ajax features you can choose among different Ajax frameworks, each offering a set of features and tools including a client-side Java. Script framework to enable Ajax in the browser and at the server. � Although a number of different Ajax frameworks are available for ASP. NET, the most obvious one is Microsoft ASP. NET AJAX, because it comes fully integrated with the. NET 4 Framework and Visual Web Developer 2010.

Difference between Traditional and Ajax Page

Difference between Traditional and Ajax Page

Advantages of Ajax Create flicker-free pages that enable you to refresh portions of the

Advantages of Ajax Create flicker-free pages that enable you to refresh portions of the page without a full reload and without affecting other parts of the page. � Provide feedback to your users during these page refreshes. � Update sections of a page and call server-side code on a scheduled basis using a timer. � Access server-side web services and page methods and work with the data they return. � Use the rich, client-side programming framework to access and modify elements in your page, and get access to a code model and type system that looks similar to that of the. NET Framework �

Features � ASP. NET AJAX consists of two important parts: �The ASP. NET AJAX

Features � ASP. NET AJAX consists of two important parts: �The ASP. NET AJAX Server Controls and �The client-side ASP. NET AJAX Library.

USING AJAX in ASP. NET � ASP. NET AJAX is fully integrated in ASP.

USING AJAX in ASP. NET � ASP. NET AJAX is fully integrated in ASP. NET and VWD, which means you can start using it right away. Each new ASP. NET 4 web project you create in VWD is already Ajax-enabled. � In addition, the Toolbox contains an AJAX Extensions category with a number of Ajaxrelated controls that you can use in your pages. Visual Web Developer also support with Intelli. Sense for the controls at the server as well as for the client-side Java. Script you’ll write to interact with the client page and code running on the server.

Creating Flicker free Web Pages To avoid full postbacks in your ASPX pages and

Creating Flicker free Web Pages To avoid full postbacks in your ASPX pages and update only part of the page, you can use the Update. Panel server control. � For this control to operate correctly, you also need a Script. Manager control. � If you’re going to use Ajax functionality in many of your ASPX pages, you can place the Script. Manager in the master page, so it’s available in all pages that are based on this master. � You can only have one Script. Manager page, so if you add one to a master page, you can’t add another one to a content page. � In order to access a Script. Manager control that is defined in a master page from a content page, you can use the Script. Manager. Proxy as explained later. �

The Update. Panel Control � The Update. Panel control is a key component in

The Update. Panel Control � The Update. Panel control is a key component in creating flicker-free pages. In its most basic application, you simply wrap the control around content you want to update, add a Script. Manager to the page, and you’re done. Whenever one of the controls within the Update. Panel causes a postback to the server, only the content within that Update. Panel is refreshed.

Try it Out: First with flicker than with AJAX 1. Create a new Web

Try it Out: First with flicker than with AJAX 1. Create a new Web Site 2. Create a new webform and drag a Label control and a Button control from the Toolbox. 3. Use the Properties Grid to clear the Text property of the Label control. To do this, right-click the Text property label in the Properties Grid and choose Reset. Double-click the grey and read-only area of the page in Design View to set up a handler for its Load event and add the following code to the handler that VWD added for you: protected void Button 1_Click(object sender, Event. Args e) { Label 1. Text = System. Date. Time. Now. To. String(); } 5. Save all your changes and press Ctrl+F 5 to open the page in your browser. The Label displays the current date and time. Click the Button control a few times. 4. � Note that each time you click the button, the page flickers and is then redrawn, displaying the updated date and time.

Try it Out: First with flicker than with AJAX 1. Create a new Web

Try it Out: First with flicker than with AJAX 1. Create a new Web Site Create a new webform 3. Drop Script manager from the Ajax Extensions tab of the toolbox 4. Drop an update panel also and into the update panel: 1. Drag a Label control and a Button control from the Toolbox. 2. Use the Properties Grid to clear the Text property of the Label control. To do this, right-click the Text property label in the Properties Grid and choose Reset. 3. Double-click the grey and read-only area of the page in Design View to set up a handler for its Load event and add the following code to the handler that VWD added for you: protected void Button 1_Click(object sender, Event. Args e) { Label 1. Text = System. Date. Time. Now. To. String(); } 5. Save all your changes and press Ctrl+F 5 to open the page in your browser. The Label displays the current date and time. Click the Button control a few times. 2. � Note that this time the page is not flickering. The source is in the next slide

Source of aspx file � � � � <asp: Script. Manager ID="script. Manager 1"

Source of aspx file � � � � <asp: Script. Manager ID="script. Manager 1" runat="server"></asp: Script. Manager> <asp: Update. Panel ID="updatepanel 1" runat="server"> <Content. Template> <asp: Label ID="Label 1" runat="server"></asp: Label> <asp: Button ID="Button 1" runat="server" Text="Button" onclick="Button 1_Click" /> </Content. Template> </asp: Update. Panel>

Common Update. Panel Properties � Children. As. Triggers �This property determines whether controls located

Common Update. Panel Properties � Children. As. Triggers �This property determines whether controls located within the Update. Panel can cause a refresh of the Update. Panel. The default value is True, as you saw in the previous exercise. When you set this value to False, you have to set the Update. Mode to Conditional. Note that controls defined within the Update. Panel still cause a postback to the server with this property set to False; they just don’t update the panel automatically anymore. � Triggers �The Triggers collection contains Post. Back. Trigger and Async. Post. Back. Trigger elements. The first is useful if you want to force a complete page refresh, whereas the latter is useful if you want to update an Update. Panel with a control that is defined outside the panel.

Common Update. Panel Properties (cntd) � Render. Mode �This property can be set to

Common Update. Panel Properties (cntd) � Render. Mode �This property can be set to Block or Inline to indicate whether the Update. Panel renders itself as a <div> or <span> element. � Update. Mode �This property determines whether the control is always refreshed (the Update. Mode is set to Always) or only under certain conditions, for example, when one of the controls defined in the <Triggers> element is causing a postback (the Update. Mode is set to Conditional). � Content. Template �Although not visible in the Properties Grid for the Update. Panel, the <Content. Template> is an important property of the Update. Panel. It’s the container in which you place controls as children of the Update. Panel. If you forget this required Content. Template, VWD gives you a warning/error.

Words on Update Panel � Useful as the Update. Panel seems (and is), its

Words on Update Panel � Useful as the Update. Panel seems (and is), its usage comes at a price. Although it appears if only part of the page is refreshed, the entire page (and all of its form data) is still posted back to the server. At the server, the page still goes through its normal life cycle and then sends back the HTML that is needed to update the page. However, the data that is sent back isn’t in a very optimal format because it contains some overhead data (required by ASP. NET AJAX to understand how to interpret it). This means that the Update. Panel carries some overhead in terms of form posts, page processing, and network traffic. � As demonstrated in the previous try out, the Update. Panel control is capable of refreshing parts of a page. Controls that are defined either inside the Update. Panel or outside of it can cause a refresh of the Update. Panel. However, in order to function, the Update. Panel needs a Script. Manager control that manages the client-side Java. Script, among other things.

The Script. Manager Control � The Script. Manager control serves as the bridge between

The Script. Manager Control � The Script. Manager control serves as the bridge between the client page and the server. It managesscript resources (the Java. Script files used at the client), takes care of partial-page updates as shownearlier, and handles interaction with your web site for things like web services and the ASP. NET application services such as membership, roles, and profile. � You can also place the Script. Manager in a master page so it becomes available throughout the entire site

Common Script. Manager Properties � Allow. Custom. Errors. Redirect � This property determines whether

Common Script. Manager Properties � Allow. Custom. Errors. Redirect � This property determines whether errors that occur during an Ajax operation cause the customized error page to be loaded. The default is True; with a setting of False the error is shown as a Java. Script alert window in the browser or is hidden from the client when debugging is disabled. Note that if you haven’t configured any customized error page, the error is always shown as a Java. Script alert, regardless of the value of this setting. � Async. Post. Back. Error. Message � When you’re not using customized error pages, this property enables you to customize the error message that users see when an Ajax error occurs. It enables you to hide the dirty details from the user and instead present them a more friendly error message. � Enable. Page. Methods � This property determines whether client code is allowed to call methods defined in the page. You see how this works later.

Common Script. Manager Properties (cntd) � Enable. Partial. Rendering � This property determines whether

Common Script. Manager Properties (cntd) � Enable. Partial. Rendering � This property determines whether the Script. Manager supportsthe partial rendering of the page using Update. Panel controls. You should leave this setting to True, unless you want to block the partial updates for the entire page. � Enable. Cdn � With this property set to True, ASP. NET includes links to the client-side framework files on Microsoft’s Content Delivery Network, rather than on your own server. This could save you some bandwidth and may speed up the initial load of the page if the user already had a cached copy of the files from visiting another site using these files. � Microsoft. Ajax. Mode � Determines whether the Microsoft AJAX client library is included. This setting enables you to use the Script. Manager for serverrelated tasks (like registering client scripts) without embedding the client-side framework in the page.

Common Script. Manager Properties (cntd) � Scripts �The <Scripts> child element of the Script.

Common Script. Manager Properties (cntd) � Scripts �The <Scripts> child element of the Script. Manager control enables you to additional Java. Script files that must be downloaded by the client at runtime. � Composite. Script �Just like the <Scripts> element, the <Composite. Script> element enables you to additional Java. Script files. However, files registered under <Composite. Script> are combined into a single, downloadable file, minimizing network overhead and improving performance. � Services �The <Services> element enables you to define web services that are accessible by your client-side pages. You see how to use web services in the second half of this chapter.

The Update. Progress Control � You connect the Update. Progress control to an Update.

The Update. Progress Control � You connect the Update. Progress control to an Update. Panel using the Associated. Update. Panel. ID property. Its contents, defined in the <Progress. Template> element, are then displayed whenever the associated Update. Panel is busy refreshing. Additional Properties:

Try it Out: All together 1. 2. 3. 4. 5. Create a new Web

Try it Out: All together 1. 2. 3. 4. 5. Create a new Web Site Create a new webform Drop Script manager from the Ajax Extensions tab of the toolbox Drop an update panel also and into the update panel: 1. Drag a Label control and a Button control from the Toolbox. 2. Use the Properties Grid to clear the Text property of the Label control. To do this, right-click the Text property label in the Properties Grid and choose Reset. 3. Double-click the grey and read-only area of the page in Design View to set up a handler for its Load event and add the following code to the handler that VWD added for you: protected void Page_Load(object sender, Event. Args e) { Label 1. Text = System. Date. Time. Now. To. String(); System. Threading. Thread. Sleep(5000); // to force the system to wait a bit } Drag an Update. Progress control Set its Associated. Update. Panel. ID to Update. Panel 1, the ID of the Update. Panel defined earlier in the page.

Try it Out: All together Between the <Update. Progress> tags create a <Progress. Template>,

Try it Out: All together Between the <Update. Progress> tags create a <Progress. Template>, and within this template, write “Please wait. . ”. 7. You should end up with this code: 6. � </asp: Update. Panel> � <asp: Update. Progress ID=”Update. Progress 1” runat=”server” � Associated. Update. Panel. ID=”Update. Panel 1”> � <Progress. Template> � Please Wait. . . � </Progress. Template> � </asp: Update. Progress> � Save all your changes and press Ctrl+F 5 to open the page in your browser. The Label displays the current date and time. Click the Button control a few times.

The Timer Control � The Timer control that you find in the AJAX Extensions

The Timer Control � The Timer control that you find in the AJAX Extensions category of the Toolbox is great for executing server-side code on a repetitive basis. � The Timer control is pretty simple to use. At a specified interval, the control fires its Tick event. Inside an event handler for this event you can execute any code you see fit. The following code snippet shows the markup for a simple Update. Panel and a Timer control that you can place inside a content page based on your master page (assuming the master page already contains the required Script. Manager): � � � � <asp: Update. Panel ID=”Update. Panel 1” runat=”server”> <Content. Template> <asp: Label ID=”Label 1” runat=”server”></asp: Label> <asp: Timer ID=”Timer 1” runat=”server” Interval=” 1000” On. Tick=”Timer 1_Tick” /> </Content. Template> </asp: Update. Panel> And then for timer tick after settinmg the interval � � protected void Timer 1_Tick(object sender, Event. Args e) { Label 1. Text = System. Date. Time. Now. To. String(); }

Using Web Services and Page Methods in AJAX Web Sites � The ability to

Using Web Services and Page Methods in AJAX Web Sites � The ability to call web services and page methods from an Ajax-enabled ASP. NET web site is a great addition to our web development toolkit. Being able to call a web service or page method means it’s now much easier to access data at the server from client-side code, giving you a great alternative to full postbacks.

What are Web Services � Web services are essentially methods that you can call

What are Web Services � Web services are essentially methods that you can call over the Internet and that can optionally return data to the calling code. This makes them ideal for exchanging data between different systems. � Because web services are based on solid and wellunderstood standards, they make it easy to exchange data between different types of platforms and systems. � For example, with a web service it’s possible to exchange data between an ASP. NET web site running on Microsoft Windows and a PHP-based site running on Linux. But at the same time, it’s also possible to exchange data between an ASP. NET web site and a client browser using Java. Script.

What are Web Services � To change a standard method that returns a string

What are Web Services � To change a standard method that returns a string into a web method, you would apply the following attribute: [Web. Method] public string Hello. World(string your. Name) { return string. Format(“Hello {0}”, your. Name); } � With this attribute in place, you signal to the ASP. NET runtime that you really want to expose this method as a web method that can be called from client-side code. This also enables you to create other methods in the same class that are not exposed as web services automatically, giving you flexibility in determining what to open up for the outside world.

Creating Web Services 1. 2. 3. 4. 5. 6. Create a new folder called

Creating Web Services 1. 2. 3. 4. 5. 6. Create a new folder called Web. Services in the root of your site to group all web services in the site in a single folder. This is not required, but helps in organizing your site. Next, right-click this new folder and choose Add New Item. Click the Web Service item (don’t accidentally choose WCF Service as that results in a different type of service), make sure that your preferred programming language and Place Code in Separate File are selected, and call the service Name. Service. Click Add to add the service to the site. Notice how the. asmx file is added to the Web. Services folder and the Code Behind file (. vb or. cs) is placed in the site’s App_Code folder. Open the Name. Service Code Behind file from the App_Code folder and change the code for the Hello. World method so it accepts a string and returns a personalized greeting. You should end up with code like this: [Web. Method] public string Hello. World(string your. Name) { return string. Format(“Hello {0}”, your. Name); } Save all your changes, right-click Name. Service. asmx in the Solution Explorer, and choose View in Browser. Once the browser is done loading, you get a page that lists all the public web services defined in the Name. Service. asmx service. Click the Hello. World link and you are taken to a page where you can test out the service. Type your name in the your. Name field and click Invoke. A new window opens, showing the XML that has been returned by the web service.

Using Web Services in Your Ajax Web Site Before ASP. NET AJAX, calling web

Using Web Services in Your Ajax Web Site Before ASP. NET AJAX, calling web services from a client browser and working with the data they return involved writing a lot of code, especially if you wanted it to work in all major browsers like Internet Explorer and Firefox. Fortunately, the Ajax framework shields you from all the complexity and code that is needed to consume a web service. All you need to do is add an attribute to the web service to mark it as a service that can be called by a script. Then you register the service in the Script. Manager control and write a few lines of Java. Script to invoke the service and receive its return value. � Note That: This only works for services that are defined within your own web site. �

Using Web Services in Your Ajax Web Site 1. Configuring the Web Service �

Using Web Services in Your Ajax Web Site 1. Configuring the Web Service � Earlier you saw how to mark a method as a web method by adding an attribute. This exposes the method to the outside world. To make a web service visible by client-side script also, you need to add an attribute to the service class. If you look at the Name. Service class in the App_Code folder, you see that the template already added the attribute for you, but commented it out: �// [System. Web. Script. Services. Script. Service] � Simply uncomment the line to expose the entire service as a client-script service.

Using Web Services in Your Ajax Web Site 2. Configuring the Script Manager �

Using Web Services in Your Ajax Web Site 2. Configuring the Script Manager � When using web services, you also need to tell the Script. Manager that you want to expose your web service to client script. There are two ways to do this: ➤➤ In the Script. Manager in the master page ➤➤ In a content page that uses the web service, using the Script. Manager. Proxy class � For example, to make the Name. Service. asmx service you created available in all pages in your site, you’d add the following highlighted code to the master page: ○ <asp: Script. Manager ID=”Script. Manager 1” runat=”server”> ○ <Services> ○ <asp: Service. Reference Path=”~/Web. Services/Name. Service. asmx” /> ○ </Services> ○ </asp: Script. Manager>

Using Web Services in Your Ajax Web Site � When you have the Script.

Using Web Services in Your Ajax Web Site � When you have the Script. Manager. Proxy in place, you add the exact same <Services> element to it as you saw with the Script. Manager itself: ○ <asp: Script. Manager. Proxy ID=”Script. Manager. Proxy 1” runat=”server”> ○ <Services> ○ <asp: Service. Reference Path=”~/Web. Services/Name. Service. asmx” /> ○ </Services> ○ </asp: Script. Manager. Proxy>

Try it out: Calling Web Services from Client-Side Code � In this exercise you

Try it out: Calling Web Services from Client-Side Code � In this exercise you register your web service in a Script. Manager. Proxy control so it becomes available in one page only. In addition, you modify the service so its methods are accessible by script. Finally, you write some client-side Java. Script code that accesses the service and then displays its return value.

Try it out: Calling Web Services from Client-Side Code (cntd) 1. Create a web

Try it out: Calling Web Services from Client-Side Code (cntd) 1. Create a web site add a web service naming it as Name. Service and than , the first thing you need to do is add the Script. Service attribute to your service class to mark it as callable by client-side script. To do this, open the file Name. Service. cs from the App_Code folder and uncomment the line that defines the attribute. You should end up with this code: [System. Web. Script. Services. Script. Service] public class Name. Service : System. Web. Services. Web. Service { 2. While you’re at it, change the Namespace property of the Web. Service attribute. By default, the namespace looks like this: C# [Web. Service(Namespace = “http: //tempuri. org/”)] Although this name is fine during development of your web services, it should really reflect the unique name of your service when you put it in a production environment in order to avoid possible conflicts with other services carrying the same names or types. If you have your own domain name, you can change the namespace to something like http: //www. yourdomain. com/. If you don’t have your own domain, don’t worry about it. Even with the Namespace set to the default value of http: //tempuri. org/, things will work fine.

Try it out: Calling Web Services from Client-Side Code (cntd) � 3. The next

Try it out: Calling Web Services from Client-Side Code (cntd) � 3. The next step is creating a page that uses the service and then registers it using a Script. Manager. Proxy control. Add a new Web Form call it Web. Services. aspx. Once you’ve added the page, drag a Script. Manager control from the AJAX Extensions category of the Toolbox. � 4. Within the Script. Manager element, add a <Services> element that in turn contains a Service. Reference with its Path set to the Name. Service you created earlier. Note that Intelli. Sense helps you pick the right file as soon as you type Path=” by showing you a list with files. Click Pick URL at the bottom of the list and browse to the service file in the Web. Services folder. You should end up with this code in the Web. Services. aspx page: <asp: Content ID=”Content 2” Content. Place. Holder. ID=”cp. Main. Content” runat=”Server”> <asp: Script. Manager ID=”Script. Manager” runat=”server”> <Services> <asp: Service. Reference Path=”~/Web. Services/Name. Service. asmx” /> </Services> </asp: Script. Manager. Proxy> </asp: Content> � � � �

Try it out: Calling Web Services from Client-Side Code (cntd) � 5. Right below

Try it out: Calling Web Services from Client-Side Code (cntd) � 5. Right below the closing tag of the <Script. Manager>, add an Input (Text) and an Input (Button) by dragging them from the HTML category of the Toolbox. By using plain HTML elements and not ASP. NET Server Controls, you can see that the code you are going to write really executes at the client. Set the id of the text box to Your. Name and the id of the button to Say. Hello. Set the value of the button to Say Hello. You should end up with this markup: � </asp: Script. Manager> <input id=”Your. Name” type=”text” /> <input id=”Say. Hello” type=”button” value=”Say Hello” /> � � � � � 6. Below these two lines, add a client-side Java. Script block with the following code: <input id=”Say. Hello” type=”button” value=”Say Hello” /> <script type=”text/javascript”> function Hello. World() { var your. Name = $get(‘Your. Name’). value; Name. Service. Hello. World(your. Name, Hello. World. Callback); } function Hello. World. Callback(result) { alert(result); } $add. Handler($get(‘Say. Hello’), ‘click’, Hello. World); </script> 7. Save all your changes by pressing Ctrl+Shift+S, and then request the page Web. Services. aspx in your browser. Enter your name and click the Say Hello button. If everything turned out well, you should be greeted with a message from the web service, repeating your name.

Introducing Page Methods � Although web services are extremely useful and pretty easy to

Introducing Page Methods � Although web services are extremely useful and pretty easy to create, they may be a bit of overkill at times. Sometimes you just need to send and receive a tiny bit of information to and from the page you’re currently working with. You can do this using page methods. � Page methods and web services have a few things in common. In both cases, you can call them at the client using very little code. You can send data to them, and receive data back. Additionally, when calling them you can define success and failure callback methods. What’s different is that page methods are defined directly in an existing ASPX page instead of a separate ASMX service file. You can only call them from script running within that page. That makes them ideal for small, simple functionality that is limited in scope to the current page.

Introducing Page Methods � As a preliminary: �To enable page methods you need to

Introducing Page Methods � As a preliminary: �To enable page methods you need to set the property Enable. Page. Methods of the Script. Manager control to True. You cannot set this property on the Script. Manager. Proxy class so you need to set it on the Script. Manager control directly. Once you have enabled page methods, setting them up and using them is a two step process: 1. Create a public and static method in the Code Behind of the page you’re working with. You need to apply the [Web. Method] attribute to this method. The method can optionally receive data through its parameters and optionally return some data. 2. Write the necessary Java. Script to call the page method and work with its result.

Try It Out Calling Page Methods from Client-Side Code � Create a new website

Try It Out Calling Page Methods from Client-Side Code � Create a new website add a web form named Web. Services. Then add scriptmanager and set its enablepagemethods to true. � Open the Code Behind of Web. Services. aspx in the folder and add the following server side method within the Web. Services class: [Web. Method] public static string Hello. World(string your. Name) { return string. Format(“Hello {0}”, your. Name); } � Notice how this code is almost identical to what you defined in the web service, including the Web. Method attribute. The only difference is the inclusion of the static. � The Webmethod attribute won’t be recognized directly. To fix this, type the following using statement: using System. Web. Services; � Switch to Markup View and create a copy of the HTML button you created earlier, set its id to Say. Hello. Page. Method and change its value to better describe what the button does. You should end up with code like this: ○ � Set up a handler for the button’s client click event, similar to the one you created earlier. Use Hello. World. Page. Method as the client method to call: ○ � <input id=”Say. Hello. Page. Method” type=”button” value=”Say Hello with a Page Method” /> $add. Handler($get(‘Say. Hello. Page. Method’), ‘click’, Hello. World. Page. Method); Implement the Hello. World. Page. Method method as follows: function Hello. World. Page. Method() { var your. Name = $get(‘Your. Name’). value; Page. Methods. Hello. World(your. Name, Hello. World. Callback); } function Hello. World. Callback(result) { alert(result); }

Further Study � Another great resource is the official ASP. NET AJAX documentation on

Further Study � Another great resource is the official ASP. NET AJAX documentation on the MSDN site, which you can find at http: //tinyurl. com/Ajax. Client 4. Here you can find a fully documented list of the various namespaces and all the types and members they contain.