Posts Tagged ‘ExtJS Grid ASP.NET Ajax WCF C#’

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: 22% [?]

Share