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
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 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.)
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 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.)
AJAX Features in ASP.NET MVC
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)
{
};
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
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
Live Data Binding using ASP.NET AJAX 4.0 Preview 4
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. 3. src="../scripts/MicrosoftAjaxTemplates.debug.js">
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="*">
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. 3. src="../scripts/MicrosoftAjaxTemplates.debug.js">
4.
Or you can use ScriptReferences under a ScriptManager tag:
1.
2.
3.
5.
7.
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.
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.
-
3.{{ Name }}
4.{{ Address }}
5.
2.
6.
-
{{ Name }}
{{ Address }}
2. Setting the data property of the control through code: This approach can be implemented as follows:
1.
9.
-
11.{{ Name }}
12.{{ Address }}
13.
10.
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.
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.
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.