ExtJS and ASP.Net Part 2 – WCF Communication

In ExtJS and ASP.NET Part 1- Setup I talked about how to set up extjs in asp.net.

Now it is time to get our hands dirty to actually do something with extjs in our asp.net project. The first thing I would have been interested in is how extjs can talk to server. It was a bit of struggle for me in the early days due to the fact that most of the examples and documents about server communication of extjs are in php. Here I would like to share with you all the tricks I have learned from my experience.

Bear in mind there are many ways for extjs to talk to asp.net application, the example I have here is just one of them, and it has been proven to be reliable, easy to set up and most important a prove of concept, so that you can use in your project.

Normally to serve client ajax calls, server functions can be a SOAP web service, a static web method or json wcf.

I like to use configuration free json based wcf web services to serve client side ajax calls because it is relatively easy to set up, footprint of bandwidth is small. Some time the configuration free approach does have some its limits, but I am sure that in a short period of time you will not be bothered by them, I am planning another article on how to configure a configuration free wcf web service.

Initially when I first played with extjs, I was very confused by ajax calls made by different components which use different methods and most of time have hidden built in parameters, one of the problem solving method is to separate concern, so I will start from the most simple scenario: make a request. For a simple task like this to be successful, there are still a few hurdles to get past, good news is that is where all the problems are, and once you get past them, you can put them behind you and get on with your own business.

Hurdle 1: Use right header
We all know when you make ajax calls, they can either be ‘GET’ or ‘POST’(there are new methods that supported by REST services, but I have not had any experience of that), I will present examples for both scenarios

To make a ‘GET’ request is simple:

  var myparams1 = new Object();
  myparams1.id = 1;
  Ext.Ajax.request({
        url: 'Service2.svc/GetMoviesMovieGet',
        params: myparams1,
        method: 'GET',
        success: function(response, options) {
               // response callback

               // display literal output from response
               var s = response.responseText;

                // decode text into Json object
                var treedata = (Ext.decode(response.responseText)).d;

                 //tpl.apply(treedata);
            },
         failure: function(response, options) {
                    Ext.MessageBox.alert('Failed', 'Unable to get');
                }

            });

On server, service level:

[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode =
          AspNetCompatibilityRequirementsMode.Required)]
[ServiceBehaviorAttribute(IncludeExceptionDetailInFaults = true)]
public class Service2 
{
}

On server, method declaration

 [OperationContract]
 [WebInvoke(Method = "GET", BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json)]
    public Movie[] GetMoviesMovieGet(int id)
    {
    }

To make a ‘POST ’request like this :

  var myparams = { 'id': 1 };
  Ext.Ajax.request({
                    url: 'Service1.svc/getStaticCheckTreeData',
                    params: Ext.encode(myparams),
                    method: 'POST',
                    headers: this.header || { 'Content-Type': 'application/json;charset=utf-8' },
                    success: function(response, options) {
                        // response callback

                        // display literal output from response
                        var s = response.responseText;

                        // decode text into Json object
                        treedata = (Ext.decode(response.responseText)).d;

                        // ...
                   
                           },
                        failure: function(response, options) {
                      
                            Ext.MessageBox.alert('Failed', 'Unable to get');
                        }

                    });

On server, method declaration:

 [OperationContract]
    [WebInvoke(BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json)]
    public CheckTreeNode[] getStaticCheckTreeData(int id)
    {
    }

Please be aware of ‘headers’ setting, wcf uses the header of incoming calls to deserialize, the default extjs post header is ‘application/x-www-form-urlencoded; charset=UTF-8’, this can cause a server side exception like :

The incoming message has an unexpected message format ‘Raw’. The expected message formats for the operation are ‘Xml’, ‘Json’…

The trick is to override the header content type for every post call.

Hurdle 2: Right parameter wiring

For ‘GET’, you just need to pass in the parameter object, but for ‘POST’, you need to encode the parameter object, I do not know if you have noticed that here in my examples I used two different ways to create the parameter object, as I like to program in object oriented way in javascript as much as I do in other languages, so I prefer the object way , especially when the object gets complicated.

On server side, the parameter name must match with field name of client side parameter object, as of data types wcf has no problem to understand int and string json parameters, but it does have problem with date and boolean types. If you have worked with jquery, we normally need to add a timestamp parameter for ‘GET’ calls to bypass the browser caching, this is not necessary for extjs, you might have noticed that every ‘GET’ call from extjs already attached a _dc field, and also it poses no problem if you do not use this param in wcf interface.

Hurdle 3: Decode response from server

Congratulations there is only last step to go to actually meet with the guest from server, default wcf json serialization put contents under a wrapping ‘d’ field, as long as you have taken this into account, you should have no problem to access data. As we are handling the response as a string, so we have to use ext.decode to convert string into a javascript object.

Have fun.

Tags: ,

This entry was posted on Wednesday, July 28th, 2010 at 1:58 am and is filed under ASP.NET, Javascript. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

18 Responses to “ExtJS and ASP.Net Part 2 – WCF Communication”

  1. Cleo Hobb says:

    Nice overview, it got all I needed.

  2. Very cool information. Thanks for this. Keep up the good work…

  3. backlinks says:

    Really informative blog post here my friend. I just wanted to comment & say keep up the quality work. I’ve bookmarked your blog just now and I’ll be back to read more in the future my friend! Also nice colors on the layout it goes well with the blog in my humble opinion 🙂

  4. Quincy Peres says:

    Wow this is a great site.. I’m love it.. good resource

  5. I like the blog, but could not find how to subscribe to receive the updates by email. Can you please let me know?

  6. Peggy Yuhas says:

    I can’t believe it how you surprise me each time, keep the good work, thanks man!

  7. Alita Abron says:

    You are making lots of excellent arguments in this particular blog post nevertheless its difficult in my opinion to focus on this content on the complicated theme!

  8. ExtJS and ASP.Net Part 2 – WCF Communication…

    Now it is time to get our hands dirty to actually do something with extjs in our asp.net project. The first thing I would have been interested in is how extjs can talk to server. It was a bit of struggle for me in the early days due to the fact that mo…

  9. Zeeshan says:

    dear,

    what if i don’t want to use wcf service but want to get the data from database to populate text boxes with student data.

    • CleanCodeNZ says:

      ExtJS is a javascript control not an asp.net server control , data that are used to populate ExtJS controls can be requested through WCF services, if you do not want this, then you may look at server controls like asp:textbox control, or you have a chance to populate javascript objects on page load.

  10. Franchise says:

    Does this pluin work with WP3.2.1?
    I am not seeing Geo Posts->Add new in my Admin area.

  11. Jason says:

    Thanks, it really helps a lot.

  12. gk says:

    +1 & gj for “Please be aware of ‘headers’ setting”

  13. cccec says:

    I am new to ExtJS, trying to find a straightforward example for ExtJS & WCF communication..
    I got this example working here, but only with IE, with Firefox and Chrome the request is done with OPTIONS method (not GET, like IE does) and fails. Is the problem on the ExtJS side or WCF service side?

  14. Joe says:

    Using code was the only example I found that worked. However I am trying to bind the response to a store then to a grid. I can see the ajax call is successful and json response but cannot get the store to load or see data in grid.

    var myStore = Ext.create(‘Ext.data.ArrayStore’, {
    model: ‘User’
    });

    Ext.Ajax.request({
    url: ‘http://localhost:/WCFService/WebService1.asmx/getValue’,
    method: ‘GET’,
    success: function (response, options) {
    var s = response.responseText;
    Ext.MessageBox.alert(s, ‘WOO WOO’);
    myStore.load(s);
    },
    failure: function (response, options) {
    Ext.MessageBox.alert(‘FAILED MOFO’, ‘Unable to GET’);
    }
    });

    var grid = Ext.create(‘Ext.grid.Panel’, {
    store: myStore,
    stateful: true,
    stateId: ‘stateGrid’,
    columns: [

Leave a Reply

*