Categorized | ASP.NET

Using ExtJS Grid with ASP.NET Ajax WCF WebServices & C#

I have been using ExtJS Javascript framework from long time and it is Intuitive, very very extensive, great DOM manipulation, solid effects. The fastest to get things done when puzzling out on the commandline. As in one of my earlier post I talked about Coolite. Coolite Toolkit is an Ext official suite of ASP.NET Web Controls built on the Ext JavaScript Framework. I would really recommend to use the above instead of using ExtJS seperately with ASP.NET Framework. But, if for any reason here is the sample. Step 1: Create aspx page Simple ASPX page which enables to search by last name or first name

<%@ Page Language="C#" MasterPageFile="~/MasterPages/MasterPage.master" AutoEventWireup="true" CodeFile="UserSearch.aspx.cs" Inherits="Webforms_UserSearch" Title="Search User" %><%@ Register    Assembly="AjaxControlToolkit"    Namespace="AjaxControlToolkit"    TagPrefix="ajaxToolkit" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<asp:ScriptManager runat="server" ID="scriptManagerId">
    <Scripts>
        <asp:ScriptReference Path="~/Scripts/UserSearch.js" />
    </Scripts>
    <Services>
        <asp:ServiceReference  Path="~/WebServices/ExtJSWebService.asmx" />
    </Services>
</asp:ScriptManager>
    <div class="x-box-blue" style="width:500px;">
	<div class="x-box-tl"><div class="x-box-tr"><div class="x-box-tc"></div></div></div>
	<div class="x-box-ml"><div class="x-box-mr"><div class="x-box-mc" id="boxContent">
    <asp:Label ID="lblForm" runat="Server" CssClass="FormLabel" Text="User Search"></asp:Label>
	<div id="thePanel" class="FormPanel">
		<div id="theData">
			<table align="center" >
                    <tr>
                        <td  colspan="12" height="4px">
                        </td>
                    </tr>
                    <tr>
                        <td align="right">
                            <asp:Label ID="lblLastName" runat="server" AssociatedControlID="txtLastName" CssClass="Label" >Last Name</asp:Label>
                        </td>
                        <td width="4px">
                        </td>
                        <td>
                            <asp:TextBox ID="txtLastName" runat="server" CssClass="TextBox" MaxLength="50" ></asp:TextBox>
                        </td>
                        <td width="14px">
                        </td>
                        <td align="right">
                            <asp:Label ID="lblFirstName" runat="server" AssociatedControlID="txtFirstName" CssClass="Label"  >First Name</asp:Label>
                        </td>
                        <td width="4px">
                        </td>
                        <td>
                            <asp:TextBox ID="txtFirstName" runat="server" CssClass="TextBox" MaxLength="50"></asp:TextBox>
                        </td>
                    </tr>
 
                    <tr>
                        <td  colspan="12" height="4px">
                        </td>
                    </tr>
                 </table>
		</div>
	</div>
	</div></div></div>
	<div class="x-box-bl"><div class="x-box-br"><div class="x-box-bc"></div></div></div>
    </div>
    <div style="width:500px;">
    <table align="center">
    <tr>
        <td height="5px" colspan="12">
        </td>
    </tr>
    <tr>
        <td colSpan="3" height="10">
             <asp:label id="lblWarn" runat="server" CssClass="Warning" Visible="False"></asp:label>
        </td>
    </tr>
    </table>
    <table align="Center">
    <tr>
        <td>
            <asp:Button ID="btnSearch" runat="Server" Text="Search"  OnClientClick="return BindGrid();"/>
       </td>
       <td width="10px">
       </td>
       <td>
            <asp:Button ID="btnAdd" runat="Server" Text="Add"  OnClick="btnAdd_Click" CausesValidation="false"/>
       </td>
     </tr>
         <tr>
        <td height="5px" colspan="12">
        </td>
    </tr>
     </table>
    </div>
 
    <div id="grid-win" class="x-hidden">
        <div class="x-window-header">User Search</div>
        <div id="grid-user">
 
        </div>
    </div>
</asp:Content>

Step 2 :  Creating Web Service ( If you look at aspx page, i called it ExtJSWebService.asmx

using System.Text;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security.Principal;
using System.Data.Common;
using System.IO;
using System.Configuration;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Collections;
using System.Data;
 
/// <summary> 
/// Summary description for WebService 
/// </summary>
[System.Web.Services.WebService(Namespace = "MR")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class ExtJSWebService : System.Web.Services.WebService
{
    string strResponse = string.Empty;
 
    public ExtJSWebService()
    {
        //Uncomment the following line if using designed components        //InitializeComponent(); 
    }
 
    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true, XmlSerializeString = false)]
    public JSONCollection<MembershipUserCollection> GetUserCollectionJSON(int start, int limit, string i_Params, string sort, string dir)
    {
 
        UserDataSource objDS = new UserDataSource();
        MembershipUserCollection objCollection = objDS.GetUserCollection(i_Params, start, limit, sort + " " + dir);
        JSONCollection<MembershipUserCollection> objJSON = new JSONCollection<MembershipUserCollection>();
        objJSON.List = objCollection;
        objJSON.TotalCount = objDS.GetUsersCount(i_Params);
 
        return objJSON;
    }
}
 
public class JSONCollection<T>
{
    private T m_value;
    private int intCount;
 
    public T List
    {
        get
        {
            return m_value;
        }
        set
        {
            m_value = value;
        }
    }
 
    public int TotalCount
    {
        get
        {
            return this.intCount;
        }
        set
        {
            this.intCount = value;
        }
    }
 
}
 
public class MembershipUserCollection : System.Collections.ObjectModel.Collection<MembershipUser>
{
 
}
 
[Serializable]
public class MembershipUser
{
    public MembershipUser();
 
    public string ErrorMessage { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

Step 3:  Javascript by name UserSearch.js (as reference in aspx)


 

var usWin;
function BindGrid(){
        Ext.lib.Ajax.defaultPostHeader = 'application/json';
         var gridDiv = $get('grid-user');
         gridDiv.innerHTML = '';
         var fieldMap = new Ext.data.Record.create(
                    [
                        {name : 'LastName'},
                        {name : 'FirstName'}
 
                    ]);
 
                    var usDataStore = new Ext.data.Store(
                    {
                        //Note that I have renamed the web service proxy class
                        proxy: new Ext.ux.AspWebServiceProxy(
                        {
                            webServiceProxy: ExtJSWebService,
                            webServiceProxyMethod: ExtJSWebService.GetUserCollectionJSON
                        }),
                        reader: new Ext.data.JsonReader({
                                    root: 'List',
                                    totalProperty: 'TotalCount',
                                    id: 'LastName'
                        },fieldMap),
 
                        remoteSort: true
                    });
 
                    usDataStore.setDefaultSort('LastName', 'desc');
            // 5. Now you can bind this ExtJS based “Store” to any ExtJS based “GridPanel” or Select list or can use the store as a temporary data place holder for further manipulation later on.
            var usColModel = new Ext.grid.ColumnModel([
 
                {header: "Last Name", width: 105, sortable: true, dataIndex: 'LastName'},
                {header: "First Name", width: 105, sortable: true, dataIndex: 'FirstName'},
            ]);
 
            var usGrid = new Ext.grid.GridPanel({
                el:'grid-user',
                ds: usDataStore,
                cm: usColModel,
                sm: new Ext.grid.RowSelectionModel({
                   singleSelect: true
               }),
                stripeRows: true,
                bbar: new Ext.PagingToolbar({
                    pageSize: 10,
                    store: usDataStore,
                    displayInfo: true,
                    displayMsg: 'Displaying Users {0} - {1} of {2}',
                    emptyMsg: "No topics to display"
                    }),
                viewConfig: {
                    emptyText: '&lt;<span class="tag">div</span><span class="attr"> style=</span><span class="attrv">"color:Red;"</span><span class="attr"> align=</span><span class="attrv">"center"</span>&gt;No Users found...&lt;/<span class="tag">div</span>&gt;'
                },
                autoHeight:true,
                plugins:[new Ext.ux.grid.Search({
                             mode:'local'
                            ,iconCls:false
                            ,dateFormat:'m/d/Y'
                        })]
            });
            usGrid.render();
 
           usGrid.on('rowclick', function (grid, rowIndex, e){
                var record = grid.getStore().getAt(rowIndex);  // Get the Record
                var userID = record.data['LastName'];
                window.location='ManageUser.aspx?Mode=Update&amp;LastName='+LastName;
             });
 
            var paramXML = PrepareParamXML();
 
            usDataStore.on('beforeload', function() {
                        usDataStore.baseParams = {
                        i_Params: paramXML
                      };
             });
 
            usDataStore.load({params:{start:0, limit:10}});
            usDataStore.on('loadexception', function(a,conn,resp) {
                     if (resp.status == '304') {
                                //Ext.Msg.alert('Content has not changed');
                            } else if (resp.status == '401') {
                                //Ext.Msg.alert('Authentication required - You need to Login');
                            }
                });
 
        // create the window on the first click and reuse on subsequent clicks
        if(!usWin){
            usWin = new Ext.Window({
                el:'grid-win',
                layout:'fit',
                width:600,
                modal:true,
                autoHeight:true,
                closeAction:'hide',
                plain: true,
                items: [usGrid],
                buttons: [{
                    text: 'Close',
                    handler: function(){
                        usWin.hide();
                           var button = Ext.get('ctl00_ContentPlaceHolder1_btnSearch');
                           button.dom.focus();
                           var txt = Ext.get('ctl00_ContentPlaceHolder1_txtLastName');
                           txt.dom.focus();
                    }
                }]
            });
        }
        usWin.show();
        return false;
}
 
Ext.namespace('Ext.ux');
 
Ext.ux.AspWebServiceProxy = function(conn)
           {
              Ext.ux.AspWebServiceProxy.superclass.constructor.call(this);
              Ext.apply(this, conn);
           };
 
Ext.extend(Ext.ux.AspWebServiceProxy, Ext.data.DataProxy,
{
     load : function (params, reader, callback, scope, arg)
            {
               var userContext = {
                                    callback: callback,
                                    reader: reader,
                                    arg: arg,
                                    scope: scope
                                 };
 
               var proxyWrapper = this;
 
               //debugger;
               //Handles the response we get back from the web service call
               var webServiceCallback = function(response, context, methodName)
                                        {
                                            proxyWrapper.loadResponse(response, userContext, methodName);
                                        }
 
               var serviceParams = [];
 
               //Convert the params into an array of values so that they can be used in the call (note assumes that the properties on the object are in the correct order)
               for (var property in params)
               {
                  serviceParams.push(params[property]);
               }
 
               //Add the webservice callback handlers
               serviceParams.push(webServiceCallback);
               serviceParams.push(this.handleErrorResponse);
 
               //Make the actual ASP.Net web service call
               this.webServiceProxyMethod.apply(this.webServiceProxy, serviceParams);
            },
 
     handleErrorResponse : function(response, userContext, methodName)
                           {
                               window.location.reload();
//                               Ext.MessageBox.show({
//                                       title: 'Error',
//                                       msg: response.get_message(),
//                                       buttons: Ext.MessageBox.OK,
//                                       icon: Ext.MessageBox.ERROR
//                                   });
                              //alert("Error while calling method: " + methodName + "n" + response.get_message());
                           },
 
     loadResponse : function (response, userContext, methodName)
                    {
                        var result = userContext.reader.readRecords(response);
                        userContext.callback.call(userContext.scope, result, userContext.arg, true);
                    }
 
});

I’m assuming you have master page and it has reference to javascript


 

    <script type="text/javascript" src="../Scripts/ext-2.0/adapter/ext/ext-base.js"></script>
    <!-- ENDLIBS -->

    <script type="text/javascript" src="../Scripts/ext-2.0/ext-all.js"></script>
    <script type="text/javascript" src="../Scripts/Ext.ux.AspWebServiceProxy.js"></script>

Popularity: 38% [?]

  • Share/Bookmark

15 Responses to “Using ExtJS Grid with ASP.NET Ajax WCF WebServices & C#”

  1. thekindofme says:

    nice post. ExtJS has the best UI widgets!
    btw i did something similar but in asp.net mvc framework.

    http://thekindofme.wordpress.com/2009/02/05/a-grid-with-ajax-pagination-sorting-filtering-on-aspnet-mvc-with-extjs-and-ef/

    cheers!

  2. Shawn says:

    I am trying to use your example and I am unable to figure out where your PrepareParamXML function is defined and what it is supposed to be doing.

    Any help on this would be appreciated.

    Thanks.

  3. admin says:

    Shawn,

    You dont have to use this, if you dont want to pass any values to the server.

    It will be helpful if you have search screen and to capture various user inputs.

    for ex:
    PrepareParamXML function return something like this

    myFirstNamemyLastNameA< /UserSearch>“

  4. Shawn says:

    Thanks for getting back to me. I actually figured it out seconds after I posted the comment. :)

    One last thing I can’t quite figure out is why my grid only has one item in it even thought it should have at least 10.

  5. admin says:

    Check the Ext.grid.ColumnModel and Ext.data.Record.create.

  6. SYED HAMSA says:

    I have the task of sending an account information email when the admin accepts the request of the user for a new account on website.So i am planning to keep a check box on edituserprofile page , when it is checked and when we click update profile button , it should send account confirmation email to the user and uncheck the check box.Can i get any idea of the code for doing this task.

  7. admin says:

    Syed
    Can you elaborate more ?

  8. SYED HAMSA says:

    I have to incorporate the functionality of sending an conformation email to the user on button click(update profile in edituserprofile page ) when the admin accepts the request for a new user account on my website.So i am planning to keep a check box(accepted) on edituserprofile page , when it is checked and when we click update profile button , it should send confirmation email to the user stating that user can access the website now and uncheck the check box.Can i get any idea of the code for doing this task. Does this make sense. I really appreciate your diligence

  9. Harshini says:

    Iam getting an error saying GetPrintersgrid in webServiceProxy is undefined.I have followed the same example above but i get this error.Can you please help me with this issue.

  10. admin says:

    Harshini
    You must have missed something. Where did “GetPrintersgrid” comes from? I dont see anything like it. share your code then i can look at it.

  11. Harshini says:

    I have defined webservice in the ascx page as follows

  12. Harshini says:

    For some reason Iam not able to post the code in the comment secttion

  13. Harshini says:

    I have added grid filter plugin to my project. Presently it filtering locally. I wanted to do remote filtering so i changed my local: false .Can you please let me know how can i send type, field, value (which are filter parameters of a particular column) to web service

    Iam using the same example i.e Using ExtJS Grid with ASP.NET Ajax WCF WebServices

    Can you please help me regarding this issue

  14. b p sharma says:

    good article,
    thanks

Trackbacks/Pingbacks


Leave a Reply

  • Popular
  • Latest
  • Comments
  • Tags
  • Subscribe

Videos

Calendar

September 2010
M T W T F S S
« Apr    
 12345
6789101112
13141516171819
20212223242526
27282930  

Follow Us