Showing posts with label AJAX. Show all posts
Showing posts with label AJAX. Show all posts

Posting Forms the AJAX Way in ASP.NET MVC

Your Ad Here

Posting Forms the AJAX Way in ASP.NET MVC

Create AJAX-enabled HTML Forms in ASP.NET MVC Pages

There are only two ways in which a web page can place an HTTP request to a server-side URL. You can set the target URL as the action attribute of an HTML form or you can instruct the browser’s XMLHttpRequest object to reach the URL using an HTTP request. The latter scenario represents the typical AJAX scenario, where the client page gains control over the entire operation. In that case, a piece of JavaScript code does the trick of invoking the URL, passes some input data, and gets any response. Implementing this scenario in ASP.NET MVC only requires you to get familiar with and use some ad hoc tools, like the AJAX methods in the jQuery library, or in any other advanced JavaScript library with which you feel comfortable.

What if, instead, you’re a server-side person and don’t like JavaScript that much? ASP.NET MVC provides an alternative API to add AJAX capabilities to pages, while still remaining in the realm of markup and server code.

In this article, I’ll examine an AJAX-related feature of the ASP.NET MVC Framework that basically implements a form of partial rendering on top of the new ASP.NET MVC programming model. In a nutshell, I’ll discuss how to post the content of an HTML form to a server controller and update the current view without incurring a full page refresh.
The HTML Message Pattern

Before I go any further, let me briefly recall the underlying pattern we are silently applying here. As thoroughly described at www.ajaxpatterns.org, the HTML Message pattern refers to a situation in which a web page invokes a remote URL and receives a plain HTML response. The URL, whether be it a web/WCF service or a plain REST service, doesn’t return data only, but rather a UI-ready string that the caller will take and render out.

HTML Message is the pattern living behind the partial rendering approach in classic ASP.NET, and also is the pattern that some commercial libraries of controls implement to give you AJAX-enabled server controls. Two libraries that do so are Telerik RadControls and Gaiaware.

AJAX can be done in either of two ways: bring plain data to the client and arrange the UI or bring pre-arranged HTML on the client. Partial rendering clearly addresses the second option, and so it is when you use AJAX facilities in the ASP.NET MVC Framework.

The AJAX BeginForm Helper
AJAX support for ASP.NET MVC views is built in to the Ajax helper class. The class features the members listed in the table in Figure 1.
Member
Description
ActionLink
Generates an anchor tag whose action URL is based on the specified parameters.
BeginForm
Generates a
tag with an action URL that performs an AJAX operation.
RouteLink
Generates an anchor tag whose action URL is based on the specified route name.
ViewContext
An object that contains information about the view data, controller, and temporary data.
Figure 1: Members of the Ajax helper class
In particular, the BeginForm helper method generates an AJAX-enabled form tag. Here’s how to use it:
<% using (Ajax.BeginForm("GetCustomerDetails", new AjaxOptions { Confirm = "Are you sure?", LoadingElementId = "lblWait", UpdateTargetId = "pnlDetails" })) { %>
//
//

<% } %>

The first argument to BeginForm indicates the action you want to execute once the form is posted. The name of the target controller can be explicitly mentioned using one of the numerous overloads of BeginForm. If not specified, it is inferred from the content of ViewContext.

<% = Ajax.ViewContext.Controller.ToString() %>
If not explicitly specified, the default controller is the controller that ordered the rendering of the current view. A second fundamental parameter for the BeginForm method is an instance of the AjaxOptions class. The members of the AjaxOptions class are detailed in the table in Figure 2. Essentially, the AjaxOptions class lets you specify information that will help the framework carry the operation the way you want. At the very minimum, you might want to indicate the ID of the element that will receive any HTML message that the controller method may have generated on the server. The ID is set through the UpdateTargetId member of the AjaxOptions class.

HttpMethod
String property, indicates the HTTP operation to be performed. The property value is set to POST by default.
InsertionMode
Indicates how any HTML response should be inserted in the current page DOM. Feasible values for the property come from the InsertionMode enumerated type: Replace, InsertBefore, InsertAfter. The element to replace is the element pointed by the UpdateTargetId property. The default value is Replace.
LoadingElementId
String property, gets and sets the ID of the DOM element to be displayed for the time it takes to complete the request.
OnBegin
String property, gets and sets the name of an optional JavaScript function to be executed just before submitting the request.
OnComplete
String property, gets and sets the name of an optional JavaScript function to be executed once the request has completed.
OnFailure
String property, gets and sets the name of an optional JavaScript function to be executed in case of a failed request.
OnSuccess
String property, gets and sets the name of an optional JavaScript function to be executed if the request completes successfully.

UpdateTargetId

String property, gets and sets the ID of the DOM element to be updated with any HTML response coming back from the server.

Url

String property, gets and sets the actual URL the request should be sent to. If specified, the property takes priority over the action attribute of the tag.

Figure 2: Members of the AjaxOptions class



I also declared the LoadingElementId property in the preceding code snippet. This property indicates the ID of the user interface element you want to display temporarily as the request goes. The role of the LoadingElementId property has some analogy with the UpdateProgress control you may recall from classic ASP.NET partial rendering. Given the preceding code snippet that uses Ajax.BeginForm, the corresponding resulting markup you’ll find in the browser is shown in Figure 3.




Figure 3:
The resulting markup when using Ajax.BeginForm

As you can see, the onsubmit attribute points to a framework-provided object—the Sys.Mvc.AsyncForm object. The object is defined in the MicrosoftMvcAjax.js file that is referenced automatically from any AJAX-enabled ASP.NET MVC page. Figure 4 shows the source code of the class.

Sys.Mvc.AsyncForm = function Sys_Mvc_AsyncForm()
{

}
Sys.Mvc.AsyncForm.handleSubmit = function
Sys_Mvc_AsyncForm$handleSubmit(form, evt, ajaxOptions)
{
///
///
///
///
///
///
evt.preventDefault();
var body = Sys.Mvc.MvcHelpers._serializeForm(form);
Sys.Mvc.MvcHelpers._asyncRequest(form.action,
form.method || 'post', body, form, ajaxOptions);
}
Figure 4: The AsyncForm class
Without going into the nitty-gritty details of the internal members, the overall behavior of the object comes out quite clearly. The handleSubmit method first prevents the default browser event from taking place (so no browser post will ever occur). Next, it serializes to a string the current content of thetag and sends out a request using the infrastructure provided by the Microsoft AJAX library. (At the time of this writing there was no RTM version ready, but it’s possible that by the time you read this you’ll be able to plug in your favorite AJAX library and drop Microsoft’s.)
Inside the Request Cycle

As shown in Figure 4, the submission of the request begins when the _asyncRequest helper method is invoked. The first thing this method does is show you a confirmation dialog box (see Figure 5). If the user confirms, the method proceeds and determines the target URL. The target URL isn’t necessarily the form action URL being passed to the method on the command line. If the AjaxOptions object contains a non-empty Url property, this URL is used instead. Next, the OnBegin JavaScript callback is invoked, if such a callback was specified. By using this callback, you can further modify the URL programmatically, as I’ll show in a moment.
Figure 5
Figure 5: The AJAX request is about to start

The request is then sent asynchronously; when any response comes back, the OnComplete JavaScript callback is fired. Note that this callback is invoked before examining the status code of the response. If the request completed successfully, the DOM is updated and the OnSuccess callback is run. If not, no updates are made and the OnFailure callback is executed.

The progress indicator, or whatever piece of user interface constitutes the progress template, is displayed right after the invocation of the OnBegin callback and programmatically hidden right after the OnSuccess callback has been called.
Posted Data and Response

The handleSubmit JavaScript method that fires when the user clicks the submit button of the form serializes to a string the content of the form elements. The string will then have the canonical shape of an HTTP POST body, as in the code snippet shown here:

TextBox1=Dino&TextBox2=Esposito&CheckBox1=on
On the server, the target URL can retrieve these values using the ASP.NET Request.Form collection and use posted data to perform any required server action. Figure 6 shows the details of the request body for the page in Figure 5. In this case, the form includes the sole listbox whose ID is ddCustomerList. The second element you see in Figure 6 refers to an internal flag that denotes an ASP.NET MVC asynchronous call.
Figure 6
Figure 6: Sample of data posted in an ASP.NET MVC AJAX request
Earlier in the article I repeatedly mentioned the HTML Message pattern as the pattern according to which the target URL replies to a request by sending out plain HTML. In this case, the target URL is a method on a given controller class. This method is expected to return a string and have a signature like this:
public string GetCustomerDetails(string ddCustomerList)

Note that if the parameter name matches an input element in the posted data, then ASP.NET MVC can resolve the mapping automatically. In this case, the posted value of the element named ddCustomerList is assigned to the corresponding formal parameter. If not, you can give the method an empty signature and resort to the following code:

string id = Request.Form["ddCustomerList"].ToString();

The controller’s method does its own work and produces data for the response. If you design the method to return a string, you must serialize data to an HTML string, as shown here:

public string GetCustomerDetails(string ddCustomerList)
{
string id = ddCustomerList;
Customer cust = GetCustomerInSomeWay(id);
return FormatAsHtml(cust);
}

It’s nice to notice that you also can return an object—not an HTML string—from the method. In this case, the client page will still receive a string; in particular, it will be the string generated by the ToString method on the object. In other words, the following code produces an equivalent result and might be more elegant to use in some cases:

public Customer GetCustomerDetails(string ddCustomerList)
{
string id = ddCustomerList;
Customer cust = GetCustomerInSomeWay(id);
return cust;
}
:
public partial class Customer
{
public override string ToString()
{
return FormatAsHtml(this);
}
}
I’m obviously assuming that Customer is a partial class like those auto-generated by the LINQ to SQL wizard.
adapting the URL Dynamically



To top off this article, let me briefly discuss a scenario that, although not particularly common, may sometimes show up. Let’s suppose you don’t want to post data through a form. (In ASP.NET MVC, you are no longer limited to one form per page.) You have a link button and want to invoke a URL to get some HTML. In this case, you have two options. The first entails that you explicitly write a click handler for the link button and adjust the call at your convenience. The second option is using the ActionLink helper, which requires less code and benefits from services offered by the platform:



<%= Ajax.ActionLink("Details", "/GetCustomerDetails", new { id = "xxxxx" }, new AjaxOptions { HttpMethod="GET", LoadingElementId="lblWait", UpdateTargetId="pnlDetails", OnBegin="adjustURL" })%>.



The code generated by ActionLink provides for preparing the request and updates the user interface. However, it doesn’t provide an automatic mechanism for binding input data to the URL. Suppose you want to add to the URL the ID of the customer currently selected in a list. This is a no-brainer if you’re writing a click handler yourself, but does pose a challenge if you intend to use the helper ActionLink.



A possible workaround consists of placing a placeholder in the URL (such as “xxxxx” in the snippet above) and replacing that in the OnBegin callback:



function adjustURL(context)

{

var list = $("#ddCustomerList")[0];

var id = list.options[list.selectedIndex].value;

var request = context.get_request();

var url = request.get_url();

url = url.replace(/xxxxx/, id);

request.set_url(url);

}

Conclusion

AJAX in ASP.NET MVC is definitely possible, and various tools have been provided for it. In addition to using plain JavaScript code for setting up a request and updating the user interface, you can rely on a couple of powerful helpers such as ActionLink and, more importantly, BeginForm, through which you can get the ease of use of partial rendering without the burden of the viewstate.
Source
http://www.aspnetpro.com

Subscribe
Posted in Labels: , kick it on DotNetKicks.com | 190 comments

AJAX Features in ASP.NET MVC

Your Ad Here

AJAX Features in ASP.NET MVC

Discover How to Place AJAX Requests in ASP.NET MVC Applications

For a few moments when I first approached ASP.NET MVC I really thought it was the negation of AJAX. With a programming model heavily based on REST principles, I thought all that one could do is invoke a URL. And when you get, or post to, a URL, you inevitably involve the browser and get a full-page refresh. As I’ve explored it more, and as the facts have largely shown, my first impression was dead wrong. AJAX is definitely possible in ASP.NET MVC.

The role of JavaScript is clearly relevant and fundamental. The ASP.NET MVC Framework simply provides its own set of JavaScript files and utilities to make AJAX calls occur in much the same way they occur in WebForms applications. In this article I’ll go through the various aspects of the AJAX API you can leverage in ASP.NET MVC applications.

AJAX in ASP.NET MVC? Why Not!

Compared to WebForms, ASP.NET MVC provides a smarter layer of code on top of the same ASP.NET runtime.

In the WebForms model, the request that comes in is dispatched to an HTTP handler that maps the URL to a server file. It reads the content of the server file, parses that to a C# class, compiles the class into an assembly, and invokes a well-known method on the class. The well-known method is ProcessRequest, one of the members of the IHttpHandler interface that represents the public contract for any ASP.NET page. The C# class that defines the expected behavior for the page derives from a system class (the System.Web.UI.Page class). This class is nothing more than a built-in HTTP handler—albeit one of the most complex HTTP handlers ever written.

The ASP.NET MVC Framework abstracts some of the steps in the procedure just described. For example, the URL is not necessarily bound to a server file. The URL is simply the representation of the requested resource. This means that a module intercepts the request, parses the URL, and forwards the request to a controller component. The role that the page class plays in WebForms is split between controller and view in ASP.NET MVC. I dare say that ASP.NET MVC smartly refactors ASP.NET WebForms, but works on top of the same runtime environment and, therefore, according to the same set of global rules. If AJAX is possible in WebForms, it has to be possible in ASP.NET MVC, as well.

JavaScript Makes AJAX Run

At its core, AJAX is about making an out-of-band request to the web server via XMLHttpRequest. A piece of JavaScript code prepares the call, runs it asynchronously, then processes the response in a callback function. The callback function is responsible for updating the user interface with downloaded data using the DOM services. To make developers’ lives a bit easier, Microsoft provided in ASP.NET AJAX such facilities as the partial rendering API and JavaScript proxy for Web services.

To be picky, I could say that Microsoft didn’t provide a very simple API to make AJAX calls that hide the nitty-gritty details of the XMLHttpRequest object. JavaScript proxies are great, but they require a Web or WCF service at the other end. The Microsoft AJAX client library does offer a WebRequest object, but it takes a few lines of code to prepare it and make it work. Other libraries, primarily the jQuery library now included in ASP.NET AJAX, make up for this with their own API.

The package that contains the ASP.NET MVC install also includes the jQuery library, so you can use this library (or any other similar libraries) to prepare your direct AJAX calls directed at URLs of choice. This is the most natural way of having AJAX in ASP.NET MVC applications. However, Microsoft provides facilities to make AJAX happen in a way that is similar to partial rendering in WebForms.



That said, I feel the need to clarify a key point once and for all. There’s only one way of placing AJAX calls, and it’s all about using the XMLHttpRequest object. On top of this, some frameworks and JavaScript libraries have built their own infrastructure, with the sole purpose of making programming easier and faster.

Direct Scripting

I like to use the expression “direct scripting” to refer to the scenario where you have some JavaScript code that places calls to an HTTP endpoint and receives a semantic response, such as JSON data or primitive data. Direct scripting is an approach to AJAX that works in any case, as it is at the lowest possible level of abstraction. All you need in the page is a button or in general some event handler, no matter how defined. Figure 1 shows some JavaScript code that uses jQuery to attach an onclick handler to a button.


You use the Ajax.ActionLink method within code blocks, as shown here:

<%= Ajax.ActionLink("Get customers", "/GetCustomers", new AjaxOptions { OnSuccess="addCustomersEx" })%>

The code generates a hyperlink that points to the same GetCustomers method we considered earlier in the direct scripting example. The first argument you pass to the action link is the text of the hyperlink. The second argument is the controller action to invoke. Finally, the third argument is a collection of optional settings to use in the call. At the very minimum, you must specify the JavaScript callback that runs upon a successful completion of the call. The ActionLink method has several more overloads; the one shown here is the most common and simple of all.

The controller action can return anything, including JSON, JavaScript, or plain HTML markup. The callback, if specified, will handle the response and update the user interface accordingly. Here’s the source code of the addCustomersEx callback function:

function addCustomersEx(context)

{

// Grab the method’s response
var response = eval(context.get_data());
// Invoke the addCustomers function of Figure 1
// to populate the dropdown list
addCustomers(response);

};

The success callback, as well as any other callbacks you can specify in the AjaxOptions object, receives only one argument of type AjaxContext. Figure 2 shows the members of the object. To get the response as plain data, call the get_data method and pass it through the JavaScript’s eval function to transform a JSON string into a usable JavaScript object.
Member Description

get_data

Gets any data returned from the controller action.

get_insertionMode

Indicates how to treat the response (only if markup), whether to replace, prepend, or append it to the markup of the specified DOM element. The default is replace.
get_loadingElement

Indicates the DOM element to be displayed to indicate that an AJAX call is going on.

get_request


Gets the Sys.Net.WebRequest object that represents the current request.

get_response


Gets the Sys.Net.WebRequestExecutor object for the current request.

get_updateTarget


Indicates the DOM element to be automatically updated with the returned markup, if any.


The link emitted in the page takes the following form:


As you can see, AJAX in ASP.NET MVC is definitely possible, but all of it happens through JavaScript.

Partial Rendering in ASP.NET MVC

The AJAX ActionLink method also can be used to implement a sort of partial rendering. If the controller action returns HTML markup, then this content can automatically be inserted in to the inner space of the specified DOM element. To get this, simply specify the element to update in the AjaxOptions settings and, optionally, the desired insertion mode:

<%= Ajax.ActionLink("Details", "/GetCustomerDetails", new AjaxOptions { LoadingElementId="lblWait", UpdateTargetId="pnlDetails" })%>

The lblWait DOM element is displayed for the time it takes to download the response, then is hidden. The pnlDetails DOM element, instead, is updated with the content downloaded. Of course, this approach works well if the downloaded content is an HTML string. Here’s a sample controller method:

public string GetCustomerDetails(string id)

{

// Return HTML

:

}

I recommend that any element you use as the loading element be initially hidden from view using CSS.

Conclusion

In this article I’ve demonstrated the simplest way to get AJAX in an ASP.NET MVC solution. In particular, I focused on direct scripting and the AJAX ActionLink helper method. The ActionLink approach, though, also lends itself very well to implement a sort of partial rendering in ASP.NET MVC. Because of space constraints I could only scratch the surface of this topic. Next month I’ll provide full coverage of partial rendering in ASP.NET MVC, including posting an entire form to a controller. Stay tuned!

Source
http://www.aspnetpro.com

Subscribe
Posted in Labels: , kick it on DotNetKicks.com | 4 comments

Live Data Binding using ASP.NET AJAX 4.0 Preview 4

Your Ad Here

This article will give you a highlight on implementing “Live Binding”, a feature for the upcoming version of ASP.NET AJAX.

Introduction

Many of you may already be familiar with the upcoming version of ASP.NET AJAX, version 4.0. The release was out on March 12, 2009. The key features for this version are:

* ADO.NET Data Services support
* WCF and ASMX Web service integration
* ASP.NET AJAX Client Templates
* Declarative instantiation of client-side controls and behaviors
* Observable pattern for plain JavaScript objects
* Live Bindings
* Markup Extensions
* DataView control and DataContext component
* Command Bubbling
* Change tracking and identity management
* Support for managing complex links and associations between entities from multiple entity sets or tables
* Extension methods allowing change tracking and read-write client-server scenarios using other JSON services, including RESTful or JSONP based services

This preview version can be downloaded from here. This writing is mostly for highlighting the "Live Binding" feature introduced in this release of ASP.NET AJAX. This will also cover some operations on DataView control and DataContext component.
What is Live Binding?

Live binding is having the data bound in real-time. Meaning when there's any change in the data source, the changes are reflected to the data bound interface instantly and vice versa. For example if you have an interface component, like a table, bound to a data source, like an array, any change to that array from the code is reflected in the view table instantly. If you are using an edit template for updating the data of a selected row of the table, the data in the table will get updated as you change a field in your edit form if both the table and the form use "Live Binding". Pretty cool, right?
Inside Live Binding

This is all done through client-side script, JavaScript. But how does it come in action? The core of the live binding is the implementation of an "Observer" pattern. The observer pattern enables an object to be notified about changes that occur in another object. This is not an event handler based pattern which we often misuse as an observer pattern. ASP.NET AJAX 4.0 implements this pattern completely. It adds observer functionality to ordinary JavaScript objects or arrays so that they raise change notifications when they are modified through the Sys.Observer interface.
Live Binding in Action

To implement live binding, you will need the ASP.NET AJAX 4.0 framework included in your file. After downloading from here, you'll need to reference them to your file. You can use a conventional
2.
4.



Or you can use ScriptReferences under a ScriptManager tag:

1.
2.
3. 4. Path="~/scripts/MicrosoftAjax.js" />
5. 6. Path="~/scripts/MicrosoftAjaxTemplates.js" />
7. 8. Path="~/scripts/MicrosoftAjaxAdoNet.js" />
9.

10.




You can see from these references that there are 3 files in this package, an updated MicrosoftAjax.js file and 2 new files: MicrosoftAjaxTemplates.js (for the client template support) and MicrosoftAjaxAdoNet.js (for ADO.NET utilities support).

The key components used for the Live Binding are Templates, the DataView control and the DataContext class. The AdoNetDataContext class is also there for additional ADO.NET support.
DataView Control and DataContext class

This control can bind to any JavaScript object, array or even ASP.NET AJAX component. To use a DataView control in your page, the following declarative initialization process is needed:

1. 2. sys:activate="*">



The value of the "activate" attributes are the comma separated IDs for the HTML components in which the observer is applied to check for changes. Using an * here implies to activate all the HTML components to be observable. But this might get the page rendering speed to be slower.

Data can be provided to a DataView control for live binding in a number of ways.

1. Setting the data property of the control decoratively: A declarative binding can be done through assigning a value to the data property as follows:

1.

    2.

  • 3.

    {{ Name }}


    4.
    {{ Address }}

    5.

  • 6.


  • {{ Name }}

    {{ Address }}


2. Setting the data property of the control through code: This approach can be implemented as follows:

1.
9.

    10.

  • 11.

    {{ Name }}


    12.
    {{ Address }}

    13.

  • 14.


  • {{ Name }}

    {{ Address }}


3. Using WCF or ASP.NET web service as dataProvider: A WCF or ASP.NET web service can be specified in the dataProvider property of the control.

1.
    2. dataview:autofetch="true"
    3. dataview:dataprovider=employeeService.svc"
    4. dataview:fetchoperation="GetEmployeeList">
    5.

  • 6.

    {{ Name }}


    7.
    {{ Address }}

    8.

  • 9.


  • {{ Name }}

    {{ Address }}


When the DataView control’s dataProvider property is set, the DataView control will use the provider (in this case, the Web service) to fetch data by using the operation specified in the fetchOperation property.

4. Using DataContext classes as dataProvider: The DataContext class can be used as follows:

1.
6.
    7. dataview:autofetch="true"
    8. dataview:dataprovider="{{ dataContext }}"
    9. dataview:fetchoperation="GetEmployeeList">
    10.

  • 11.

    {binding Name}


    12.
    {binding Address}

    13.

  • 14.


  • {binding Name}

    {binding Address}


If you are using an ADO.NET data service, you should use the AdoNetDataContext class instead of the more general-purpose DataContext class.
One-way/One-time Binding

In the above examples you see a binding syntax like this: { { expression } } This is a one-way/one-time data binding as the expression is evaluated only once, at the time of template rendering. With one-way/one-time binding, if the source data changes after the template has been rendered, the rendered value will not be automatically updated. An example for this is:

1.

{{ Name }}



{{ Name }}



Two-way Live Binding

Another syntax is available to ensure the target value is updated with the change of source value, which is like this: { expression } In two-way live binding, the binding works in both directions. If the target value is changed (in this case, the value in the UI), the source value is automatically updated (in this case, the underlying data item). Similarly, if the source value is changed (in this case, if the underlying data value is updated externally), the target value (the value in the UI) is updated in response. As a result, target and source are always in sync.

In the following example, if the user modifies the values in the text boxes, the values in the h3 and div elements will change automatically.

1.

{{ Name }}


2.
{{ Address }}

3.
4.

{{ Name }}

{{ Address }}


The live-binding syntax is similar to binding syntax in WPF (XAML). It can be used for binding between UI and data, as in the above examples, as well as directly between UI elements, between data and properties of declaratively attached controls and components, and so on.

Additional Features

The syntax also provides functions for converting data values to rendered values, or converting back from values entered in UI to an appropriately formatted data value. The following example shows how to provide conversion functions:

1.



This similar syntax can be used to specify binding mode as well.

1.



The default binding behavior for text-boxes and other input controls is two-way and for all other controls is one-way.
Summary

With the live binding through templates, it will ease the client-side development
lot smoother for handling large amount of data. With these new features coming in the ASP.NET AJAX 4.0, life will become more fun in development. Let’s wait and see what more is coming in ASP.NET 4.0.

Subscribe
Posted in Labels: , , , kick it on DotNetKicks.com | 0 comments

Demystifying AJAX and Creating ASP.NET AJAX Applications using VS2008

Your Ad Here

Demystifying AJAX and Creating ASP.NET AJAX Applications using VS2008
This post was created after I have realized that most people gives me a blank (O.o) look when I first tell them about AJAX technologies on the web. In Malaysia, most people will mistakenly think that AJAX is a floor cleaning soap named Ajax Fabuloso due

This post was created after I have realized that most people gives me a blank (O.o) look when I first tell them about AJAX technologies on the web. In Malaysia, most people will mistakenly think that AJAX is a floor cleaning soap named Ajax Fabuloso due to its really cheesy advertisement on Malaysian TV. Football fans on the other hand always links AJAX to a famous Dutch based football club thus causing even more confusion. In this post, I will be highlighting what AJAX is (in the web development world) and how you can start creating your very own AJAX applications on ASP.NET using Visual Studio 2008 in 5 minutes.

What is AJAX!?


Simply speaking in layman terms, AJAX (shorthand word for Asynchronous Javascript and XML) is basically Javascript with the addition of XML involved as data passes through. In other words, a page can have its content changed dynamically without doing a page refresh or by going to another page. As a result, what you get is a really cool, desktop like experience on your web application because the page does not require any form of postback (refresh) to obtain/show new data.

If you have been wondering how AJAX is being used today, just refer to Facebook. Facebook is one of the popular websites to advocate AJAX and uses it frequently in almost every page. From adding your friends, chatting, checking out pictures in a gallery, getting updated news feeds and doing quizzes, most of the time, a page refresh is never used there.

As a result, your web server will also get better performance because all that is being downloaded by the client browser is just parts of the page, not the entire chunk unlike what is being done in non-AJAX pages. It also provides a more responsive and easy to use website for your visitors.

I am Interested! So how do I Create my AJAX Page?


One way to use AJAX on your web page is to use type the relevant Javascript into your HTML files. But if you are a ASP.NET developer, you can rejoice because AJAX controls and functions have already been built in into Visual Studio 2005 and 2008. This means that you can create cool AJAX applications really quickly and easily. The only thing that will stand in your way is creativity in how you want to develop your applications. In this tutorial, I will be working on Visual Studio 2008 to create a AJAX RSS Reader to get most read most read RSS news from The Star Online, a Malaysian newspaper portal. If you are doing it on Visual Studio 2005, the process should be similar.

Step 1 – Startup Visual Studio and create a New Web Application

The first part should be pretty straightforward… Just open up Visual Studio and click to File->New->Web Site to get the “New Web Site” dialog box. In the dialog box, ensure that ASP.NET Web Site is selected and then give your site’s folder a name.

After doing so, you should be getting your empty page called Default.aspx. Please ensure that you switch to Design View by clicking on the “Design” button on the bottom left of the code editor so that we can add AJAX controls into it.

Step 2: Adding your ASP.NET and AJAX Controls

AJAX controls are available inside your toolbox by default under the category “AJAX Extensions”. In order to use AJAX on your ASP.NET web application, it is COMPULSORY for you to insert a ScriptManager into your web page. This is because the script manager will be used to handle all AJAX calls or functionality by doing the necessary javascript conversion for the functions on your page.

The next control that you should have in your page should be the “UpdatePanel“. The update panel is the location of your web page where you would like functions to run without doing a page refresh. This is where I will place a GridView (a table to show the news details) and a Button which will be clicked in order for the news to be displayed on the GridView. Note: Make ensure that both your Gridview and Button is placed inside the UpdatePanel! Your design view should resemble the following:

Step 3: Add your Code Behind

Now we need to tell the button to download the news from The Star Online and place the details into the GridView. To do so, double click on your button in Design view to trigger the click event. The code should mirror the following:

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim reader As XmlTextReader = New XmlTextReader("http://thestar.com.my/rss/mostview/nation.xml")

'return a new DataSet
Dim ds As DataSet = New DataSet()
ds.ReadXml(reader)

GridView1.DataSource = ds.Tables(3)
GridView1.DataBind()
End Sub

If you want, you can basically try running your application by clicking on the debug button or pressing F5. If you get a dialog box requesting for debugging, just enable it. What you should get would be a page which will download latest news from The Star without any reloading or page refresh once you press on the button!

Step 4: Add Loading Effects

Usually in AJAX pages, you will be shown with a loading animated GIF while the data is being fetched from the server. These animated GIFs are useful to show your visitor that the site is currently fetching data. Currently in our web application, the data is being fetched asynchronously but the visitors may not be too sure whether the news is being fetched or not. But firstly, you will need to get an animated GIF for displaying the progress. You can generate and download dynamic and interesting loading GIFs from www.ajaxload.info. In this site, you can create dynamic loading animated GIFs that you want to place in your site really easily.

Since you have already got it, lets place it into our ASP.NET web page. Go back to your design view of your web page and add the control under AJAX Extensions called UpdateProgress. Place it into wherever you want the animated GIF to show when the page loads. Lastly, you must insert your animated GIF that you would like to display into the UpdateProgress Control. Your Design view for your web form should now resemble the following:

Step 5: Test your Application

Congratulations! You have successfully created your first AJAX web site. Now you can test it by debugging the application or right clicking on the Default.aspx file and clicking on “View in Browser”. You will notice the animated GIF appearing while it is fetching data from The Star, and the best part is, the page does not refresh one single bit.

But of course, your journey for AJAX does not end here. There are also many other cool AJAX features that you can play with by downloading the AJAX Control Toolkit

This toolkit is an add in to Visual Studio and contains plenty of other AJAX controls for you to try. To learn more about AJAX Control Toolkits, please head over to www.asp.net’s AJAX mini site.

Conclusion
So that is it. I hope you enjoyed this tutorial and start your own ASP.NET AJAX web application soon. If you want to get the source code without trying, please get it here. Be back for more about tech at Derek’s Tech Blog.

source: derekchan84.wordpress

Subscribe
Posted in Labels: , kick it on DotNetKicks.com | 1 comments

Using the Ajax control toolbox with jQuery (and ASP.NET MVC)

Your Ad Here

Using the Ajax control toolbox with jQuery (and ASP.NET MVC)

You may have thought that by jumping on ASP.NET MVC that you have to leave behind all the cool Ajax Control Toolbox controls.. or more than likely you realize that it’s possible to use them, but one has to be a “JavaScript Rocket Scientist” to use them.

You may have thought that by jumping on ASP.NET MVC that you have to leave behind all the cool Ajax Control Toolbox controls.. or more than likely you realize that it’s possible to use them, but one has to be a “JavaScript Rocket Scientist” to use them..

It’s really not, but you do need a couple things to use them.. First of all go here (Bertrand Le Roy’s blog) and pick up the jQuery plugin that let’s you instantiate MS Ajax Behaviors. Next go here to the Ajax Control Toolbox project and get both the ScriptFilesOnly project and the Source code as with MVC you won’t need anything but the JS files since the source/DLLs are for WebForms-related controls, but the Source code contains the debug version of the JS files which we’ll need (By the way, 6 months from now that link to the Ajax Control Toolbox will be old so you’ll probably want to get the latest release, and not the release I pointed at).

Now let’s look at how you would wire up the DropShadow behavior (aka the DropShadow Extender). First of all, we need to figure out the references. Thanks to Visual Studio 2008, this is easy. Using the text editor/view of your choice, open up the DropShadowBehavior.Debug.js from the Source project (not the ScriptOnly zip); this is located under the zip file at .\AjaxControlToolkitSource\AjaxControlToolkit\DropShadow. When you open up the file you will see the following at the top of the file:

1: ///

2: ///

3: ///

4: ///

5: ///

6: ///

7: ///

The first 3 items are all the standard MS Ajax client library, so we’ll need to reference those. Now we need to look at the last 4 items. If you open up the files from the ScriptOnly zip file, you aren’t going to find these exact named files; to find the right file look at the end of the file name to find the actual file you need to reference. You’ll also need to reference jQuery and Bertrand Le Roy plugins. Here’s what the references look like:

1:

2:

3:

4:

5:

6:

7:

8:

9:

10:

11:

Here’s how we can then make every div with a “box” class to have a drop shadow:

1: $().ready(function() {

2: $(".box").create(AjaxControlToolkit.DropShadowBehavior,

3: {

4: Opacity: 0.3,

5: Rounded: false,

6: TrackPosition: true,

7: Width: 5

8: });

9: });

See that JSON string (lines 3-8). If you look at those settings closely and compare them to the Ajax Control Toolbox documentation web site, you’ll see that these are the same settings that the extender uses which should make everything easy.

source: theruntime

Subscribe
Posted in Labels: , , kick it on DotNetKicks.com | 0 comments

AJAX Client –Side templating in ASP.NET 4.0

Your Ad Here

AJAX Client –Side templating in ASP.NET 4.0

The AJAX in ASP.NET 4.0 introducing new client data rendering features to page and component developers. It allows the developers to render JSON data from server as HTML in a highly efficient way. This post discuss about one of the AJAX features in ASP.NET


The AJAX in ASP.NET 4.0 introducing new client data rendering features to page and component developers. It allows the developers to render JSON data from server as HTML in a highly efficient way. This post discuss about one of the AJAX features in ASP.NET 4.0.

You need to download the AJAX scripts from following location to test the sample

You can test the following feature in VS 2010 and IIS 7.0.

Client-Side Template Rendering

Using this feature we can create a UI from data in a more manageable fashion. ASP.NET 4.0 includes a new template engine for client development which having the following features

· You can use expression language

· It is XHTML compliance

· Conditional rendering and loop over markup

Template Example

The sample template that you can create in ASP.NET 4.0 as follows

    sys:attach="dataview">

  • {{ Name }}


    {{ Description }}




Template is rendered with data item context. Properties of the data item can be included in the markup by using {{ Name }}. Expression block can also contain JavaScript expression that can be evaluated as string.

Instantiating a Template using DataView Control

We can effectively use client templates in ASP.NET 4.0 through DataView Control.

Here the content of the dataview control is template. If you set the data property of DataView control to an array then the template is rendered once for each item in array.

The Dataview control is automatically updated when the data changes, without need rebind. This provides a dynamic data –driven UI in browser.

xmlns:dataview="javascript:Sys.UI.DataView"
sys:activate="*">
    dataview:data="{{ imagesArray }}"
    >

  • {{ Name }}


    {{ Description }}



Subscribe
Posted in Labels: , kick it on DotNetKicks.com | 0 comments