Click here to Skip to main content
Click here to Skip to main content

ExtJS and .NET Web Services

By , 19 Jun 2009
 

Introduction

ExtJS is a very powerful JavaScript library, perfect for creating rich graphical user interfaces in a web browser. You can make applications for many purposes and integrate data from many sources and technologies using XML, JSON, or your own interchange format. On the other hand, .NET provides great server side features like Entity Framework, LINQ, and many powerful classes. In this article, I would like to show you how to integrate both technologies in the most convenient way and use the strengths from both of them.

Solution

When you are trying to access different data sources on different servers, the best way in today's world is to use Web Services. In this way, you can build SOA solutions accessible by many suppliers using different technologies. When we decided to use ExtJS as the GUI part and ASP.NET as the server part, it was ideal to use ASP.NET Web Services directly. Natively, ExtJS does not support SOAP XML data sources. You can write your own data proxy if you like, but I will show you that it is not necessary. ASP.NET Web Services, starting from version 2.0, allows you to talk in JSON format instead of SOAP XML.

Like in most cases, when you want to configure the behavior of .NET classes, you can use attributes. Here, we need to decorate the Web Service class with the ScriptService attribute (from the System.Web.Script.Services namespace), and then decorate methods with the ScriptMethod attribute. The class attribute does not need any configuration, but we have to add some to the method decorator. All we need to specify is the method response format, in this case ResponseFormat=ResponseFormat.Json, and allow it to talk to the Web Service method using GET HTTP method. That is all we need on the server side. Let's go then to the GUI part.

// Entity class declaration          
public class Agent {
    private int _agentID;
    public int AgentID { get { return _agentID; } set { _agentID = value; } }
    private string _firstName;
    public string FirstName { get { return _firstName; } set { _firstName= value; } }
    private string _lastName;
    public string LastName { get { return _lastName; } set { _lastName= value; } }

    public Agent() {}
    public Agent(int agentID, string firstName, string lastName) {
        _agentID = agentID;
        _firstName= firstName;
        _lastName= lastName;
    }
}

...

// WebService declaration  
[ScriptService]
public class Service : System.Web.Services.WebService
{
    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json, 
     UseHttpGet = true, XmlSerializeString = false)]
    public List<Agent> GetAgents() {
        List<Agent> agents = new List<Agent>();
        agents.Add( new Agent('1', 'Jelena', 'Akerhus') );
        agents.Add( new Agent('2', 'Londo', 'Molari') );

        return agents;
    }
}

This Web Service will produce a data structure looking like this:

{ "d": [{"AgentID": 1, "FirstName": "Jelena", 
  "LastName": "Akerhus"},{"AgentID": 2, 
  "FirstName": "Londo", "LastName": "Molari"}]}

We can access this data using a JSON enabled data store in ExtJS, called Ext.data.JsonStore:

// Create store          
var myStore = new Ext.data.JsonStore({
    // Load data at once
    autoLoad: true,
    // Override default http proxy settings
    proxy: new Ext.data.HttpProxy({
        // Call web service method using GET syntax
        url: 'Service.asmx/GetAgents',
        // Ask for Json response
        headers: {'Content-type': 'application/json'}
    }),
    // Root variable 
    root: 'd',
    // Record identifier
    id: 'AgentID',
    // Fields declaration
    fields: ['AgentID', 'FirstName', 'LastName']
});

And, show the obtained information using a data grid:

var grid = new Ext.grid.GridPanel({
    // Set store
    store: myStore,
    // Columns definition
    columns: [
        { dataIndex: 'AgentID' },
        { dataIndex: 'FirstName' },
        { dataIndex: 'LastName' }
    ],
    // Render grid to dom element with id set to panel
    renderTo: 'panel'
});

In this scenario, we have obtained data from an ASP.NET Web Service and showed it in an ExtJS data grid. This approach has one big disadvantage: the Web Service has to be located within the same domain. In the next article, I will show you how to perform a cross domain call from ExtJS to an ASP.NET Web Service in simple steps.

History

  • 6th May, 2009: Initial post
  • 19th June, 2009: Added project and source code

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Rafal Ziolkowski
Software Developer (Senior) Pareto PPN AS
Norway Norway
Member
Application Developer and Solutions Architect with many skills in programming languages and technolgies. Specializes in Microsoft .NET platform for last 6 years. Additionally Database Developer with wide experience in MySql, Microsoft SqlServer. Specializes in in building Workflow Software using LogicBase Studio from Transparent Logic (Now Altiris Workflow Solution). Lastly improve his skills in software development in Lotus Domino and Sharepoint. His primary goal is to improve skills in building Enterprise Architectures and Project Management.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
Questionvalid for extjs4?memberboelenski10 Mar '12 - 8:25 
Hello Rafal,
 
I was happy to find your articles for calling an aspnet webservice.
Unfortunately i can't get it working in my project with my web service.
Several things are different:
1. my webservice has input parameters
2. results not in a grid, output are coordinates needed to set center of a map
3. my project is using extjs4 and i see in the code that extjs2.2 is used. I read somewhere else that extjs4 does not include jsonstore anymore (but that is not true i found out).
 
Do you know how to deal with the above mentioned aspects? especially the newer version of extjs.
 
Jos
QuestionEnhancement of code?membermahesh__kumar__sharma22 Jan '12 - 1:12 
This is good start for extenstion JS. but i am worried about implement paging, sorting, update, function of grid. Well Thanks. for your nice article Smile | :)
GeneralMy vote of 5memberJuan Gabriel Herrera M.31 Aug '10 - 4:54 
Exelent, finally did i can use the Extjs Grid with ajax!!
GeneralNice ArticlememberDaniel Cardillo23 Jul '09 - 18:18 
I have been trying to get this exact scenario to work for a couple of days. Thanks for the tutorial.
GeneralRe: Nice ArticlememberRafal Ziolkowski30 Jul '09 - 5:41 
You are welcome Smile | :)
GeneralWeb Service parametersmemberMember 145866020 Jun '09 - 1:04 
If we need to pass the parameter to web service, how can we pass it from extjs javascript code. Please show me the sample
 
Pop K
GeneralRe: Web Service parametersmemberRafal Ziolkowski22 Jun '09 - 11:45 
Good point. Is simple words, You have to:
- specify method: 'GET' in HttpProxy
- enclosure parameter values in double or single quotes
 
When You want to reload store with parameters provided You can do that as usual:
 
...
store.load({ params: {
  // IMPORTANT! Embeeded param value in quotes. In the other case ASP.NET will throw exception
  division: '"'+d.division+'"'
}});
...
 
This is in simple words, I will prepare upgrade for article to cover this case. If You in a rush, please provide me email on private message and I will send You working example.
 
Rafal
GeneralRe: Web Service parametersmemberbryancu44 Sep '09 - 0:26 
would it look like this?
 
var store = new Ext.data.JsonStore({
autoLoad: true,
proxy: new Ext.data.HttpProxy({
url: 'Service.asmx/GetPeoples', // ASP.NET WebService call in GET format
method: 'GET',
params: {
name: 'something'
},
headers: {
'Content-type': 'application/json' // IMPORTANT! Without this FireFox will not understand WebService response
}
}),
root: 'd', // Root Json element, always 'd'
id: 'Id', // Identifier column, ExtJS needs it to recognize rows
fields: ['Id', 'FirstName', 'LastName', 'BirthDate'] // Simple definition of columns
});
Question2 yuigrid with 2 datasource in the same page doesn't work !memberDavid Zenou11 Jun '09 - 14:01 
Have you got an example with 2 yuigrid in the same page with 2 datasources (one for each) ?
 
Si tu aimes ce que tu fais , tu finis par réussir !
(french proverb of David Zenou)

AnswerRe: 2 yuigrid with 2 datasource in the same page doesn't work !memberRafal Ziolkowski11 Jun '09 - 19:14 
Hi,
 
YUIGRID? Do You mean Yahoo User Interface? Or grid from ExtJS? Because it's not completely the same.
 
Regards,
Rafal
GeneralRe: 2 yuigrid with 2 datasource in the same page doesn't work !memberDavid Zenou12 Jun '09 - 2:29 
grid form extjs Smile | :) ?
Maybe it's the same problematic with yahoo ui ?
 
Si tu aimes ce que tu fais , tu finis par réussir !
(french proverb of David Zenou)

GeneralRe: 2 yuigrid with 2 datasource in the same page doesn't work !memberRafal Ziolkowski12 Jun '09 - 2:43 
Hi,
 
You need to declare 2 separate DataSources. You can see in my example JsonStore stored in myStore variable. If You create myStore2 variable and use it with created by You grid2 Ext.grid.GridPanel then You will have 2 separate grids and stores. You can have as many stores, grids as You like and Your client's machine memory can stand Smile | :) But You have to preserve them in separate variables and connect properly to get it to work.
 
I am not sure if that is You problem. Maybe If You will send me some problematic code I could help You.
 
Regards,
Rafal
GeneralRe: 2 yuigrid with 2 datasource in the same page doesn't work !memberDavid Zenou12 Jun '09 - 3:05 
Thank you very much Rafal !
I understood what you say , have you got a .net solution with a simple example of your article code ?
Thanks
 
Si tu aimes ce que tu fais , tu finis par réussir !
(french proverb of David Zenou)

GeneralRe: 2 yuigrid with 2 datasource in the same page doesn't work !memberRafal Ziolkowski12 Jun '09 - 3:26 
Hi,
 
It's on the way Smile | :) I will add this code to the article.
Regards,
Rafal
GeneralNeed Code Solutionmembersyedalinaqvi8 Jun '09 - 11:16 
Hello Rafal,
 
I was wondering it you can share the whole project solution for your article:
 
ExtJS and .NET Web Services
 
How to use .NET Web Services in ExtJS.
 
You can reply directly to ashik.abbas@morganstanley.com.
 
Thanks.
Ashik
GeneralRe: Need Code SolutionmemberRafal Ziolkowski10 Jun '09 - 2:00 
Hi Ashik,
 
No problem. I will also add it to the article to share with public.
 
Regards,
Rafal
GeneralRe: Need Code Solutionmembersyedalinaqvi18 Jun '09 - 8:15 
Hi Rafal,
 
Thanks very much for sending the code. Unfortunately, attachments are removed from all external email sent to my company address. Can you please resend the code to my personal address: ashika@kidsmedia.net.
 
Also you had indicated you will add the code to the article. I could not see any code attached?
 
Thanks again.
Ashik
GeneralUseHttpGetmemberreneesong3 Jun '09 - 11:38 
Thanks a lot for the article! Exactly what I'm looking for since I'm using ExtJs with Asp.Net 2.0
 
Will it only work when UseHttpGet = true?
 
I tried the following:
 
1. removed UseHttpGet = true attribute from the WebMethod
2. on the client side set method = 'POST' for ExtJs Ajax
 
It seems that the server side page gets called but it never hit the method. For some reason, the method is not wired?
 
Any ideas? Really appreciate the help.
 
Thanks,
--Renee
GeneralRe: UseHttpGetmemberRafal Ziolkowski3 Jun '09 - 20:42 
Hi,
 
You are welcome Smile | :)
 
When You'll go to MSDN, it says: "Gets or sets a value that indicates whether to invoke the method by using HTTP GET.", which means if You want to have access to web service method using GET method calling format "Service.asmx/GetAgents" You have to use UseHttpGet = true. This is the only option to get access to web service method from JavaScript.
 
If You do not like to use GET method for some reasons, You could try to make a kind of proxy for Your web service as aspx page. I will (in near future) describe how to do it in easy way. It will use aspx page to handle script tag proxy calls from ExtJS - but after some modifications it could be also useful in Your case.
 
Regards,
Rafal
GeneralRe: UseHttpGetmemberreneesong9 Jun '09 - 8:38 
Hi Rafal,
 
Thanks a lot for the reply.
 
The reason I'm investigating in using "Post" is because the call to service might pass a long parameter, which could exceed the limit of "Get".
 
I think I was confused on the the UseHttpGet attribute. I thought by omitting it, it'd use HTTP "Post" instead of "Get".
 
I'm relative new to this architecture (EXTJs + WebService). Can you give me a few pointers in terms what you mean by "proxy for web service as aspx page" and "use aspx page to handle script tab proxy calls"? Appreciate any information that can get me start.
 
Looking forward to your solution too Smile | :)
 
Thanks again,
--Renee
GeneralRe: UseHttpGetmemberRafal Ziolkowski10 Jun '09 - 2:10 
Hi,
 
POST in this case is the only solution.
 
Architecture for "page proxy" solution is quite simple. You are sending data to real aspx page, this aspx page catches request (POST, GET, whatever) and redirects it to real ASP.NET webservice. I have made such solution, where only what You need in "page proxy", is inherit from my class instead of standard ASP.NET web page class and "tell" the class what to call in the background.
 
I will have little bit more time to finish article next week... If You in a hurry I can send You project solution.
 
Regards,
Rafal
GeneralRe: UseHttpGetmemberMember 221258119 Mar '11 - 6:24 
How do you use the event: selectedIndex_changed like in asp:GridView
 
Is it possible to have the same postback events in order to select a line, and Perform a Delete in the database server-side with c# language.
 
I found it more simple to do this way instead in js (see the link) :
 
http://www.sencha.com/learn/Tutorial:Using_Ext_grid_%2B_form_%2B_dialog_to_achieve_paging_list,_create,_edit,_delete_function[^]
GeneralNicememberJeffCirceo11 May '09 - 16:13 
I've always liked ExtJS I just never got around to mastering it.
 
nice work keep it up
 
Take a look at my corner of the net at Code Research Center

GeneralExt is greatmemberAbhishek Sur7 May '09 - 0:29 
I dont know why ext is removed from yahoo ui.
 
Well, anyways.. I am building a site like jsDesk. Its made perfectly with Ext.
 
Nice share.
 

GeneralRe: Ext is greatmemberRafal Ziolkowski7 May '09 - 0:55 
Probably they have some disagreement, while ext started from yui - but they went in little bit different direction.
 
Well, anyway - happy coding - I prefer ext's over yui in my projects too.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130523.1 | Last Updated 19 Jun 2009
Article Copyright 2009 by Rafal Ziolkowski
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid