Connecting ExtJS grid with Asp.net Websrvice: A step-by-step guide

I have exhausted all my efforts in attempting to retrieve the JSON data from my webservice. Despite being able to view the JSON data in Fiddler, I am facing an issue where the data is not binding with the grid. Below is the code snippet that I have been working on.

Webservice (Mywebservice.asmx)

[WebService(Namespace = "http://myServiceLink.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class SmartlinkService : System.Web.Services.WebService
{
    [WebMethod(CacheDuration = AppConsts.NONE)]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = false, XmlSerializeString = false)]
    public List<SampleClass> GetTasks()
    {
        List<SampleClass> listSampleClass = new List<SampleClass>(){
                                    new SampleClass{TaskId="1",TaskName="task1"},
                                    new SampleClass{TaskId="2",TaskName="task2"},
                                    new SampleClass{TaskId="3",TaskName="task3"},
                                    new SampleClass{TaskId="4",TaskName="task4"}
                                    };
        return listSampleClass;
    }

    [Serializable]
    public class SampleClass
    {
        public string TaskId { get; set; }
        public string TaskName { get; set; }
    }
}

User Control (UserControl.ascx)

<link href="Resources/extJS/resources/css/ext-all-debug.css" />
<script src="Resources/extJS/ext-all-debug.js" language="JavaScript" />
<script src="Resources/extJS/Ext.ux.AspWebAjaxProxy.js" ResourceType="JavaScript" />
<div class="section" runat="server" id="senchaGrid">
<h1 class="mhdr">
    Project Tasks
</h1>
<div class="content">
    <div class="swrap">
        <%--sencha grid area--%>
        <div id="topic-grid">
        </div>
    </div>
</div>

ExtJS Script Code

<script type="text/javascript" language="javascript">
/**********************************Sencha Grid Code START***********************************/
Ext.Loader.setConfig({ enabled: true });

Ext.Loader.setPath('Ext.ux', '../Resources/extjs/examples/ux');
Ext.require([
'Ext.grid.*',
'Ext.data.*',
'Ext.panel.*',
'Ext.util.*',
'Ext.toolbar.Paging',
'Ext.ux.PreviewPlugin',
'Ext.ModelManager',
'Ext.layout.container.Border',
'Ext.tip.QuickTipManager'
]);

Ext.onReady(function () {

    Ext.QuickTips.init();
    // setup the state provider, all state information will be saved to a cookie
    Ext.state.Manager.setProvider(Ext.create('Ext.state.CookieProvider'));
    Ext.namespace('EXT');

    Ext.define('myModel', {
        extend: 'Ext.data.Model',
        fields: ['TaskId', 'TaskName'],
        id: 'TaskId'
    });

    var storeData = new Ext.data.Store(
        {
            autoLoad: true,
            proxy: new Ext.ux.AspWebAjaxProxy({
                url: '/ProjectManagement/Mywebservice.asmx/GetTasks',
                actionMethods: {
                    read: 'POST'
                },
                reader: {
                    type: 'json',
                    model: 'myModel',
                    root: 'd'
                },
                headers: {
                    'Content-Type': 'application/json; charset=utf-8'
                }
            })
        });

    //var pluginExpanded = true;

    debugger;

    var myGrid = Ext.create('Ext.grid.Panel', {
        width: 1115, height: 500,
        //title: 'Manage tasks',
        store: storeData,
        //disableSelection: true,
        //stateful: true,
        //stateId: 'stateGrid',
        loadMask: true,
        // grid columns
        columns: [
            { text: 'TaskId', dataIndex: 'TaskId', header: 'Row #'  },
            { text: 'TaskName', dataIndex: 'TaskName', header: 'Task Name'  }
            ],

        // paging bar on the bottom
        bbar: Ext.create('Ext.PagingToolbar', {
            store: storeData,
            displayInfo: true,
            displayMsg: 'Displaying tasks {0} - {1} of {2}',
            emptyMsg: "No topics to display"
        }),
        renderTo: 'topic-grid'
    });

    // trigger the data store load
    //store.load();
});

/**************************Sencha Grid Code END******************************/

Ext.ux.AspWebAjaxProxy.js

/// <reference path="/Scripts/ext-all-debug.js" />

Ext.define('Ext.ux.AspWebAjaxProxy', {
extend: 'Ext.data.proxy.Ajax',
require: 'Ext.data',

buildRequest: function (operation) {
    var params = Ext.applyIf(operation.params || {}, this.extraParams || {}),
                            request;
    params = Ext.applyIf(params, this.getParams(params, operation));
    if (operation.id && !params.id) {
        params.id = operation.id;
    }

    params = Ext.JSON.encode(params);

    request = Ext.create('Ext.data.Request', {
        params: params,
        action: operation.action,
        records: operation.records,
        operation: operation,
        url: operation.url
    });
    request.url = this.buildUrl(request);
    operation.request = request;
    return request;
}
});

The JSON data retrieved from the server and inspected in Fiddler:

{"d":[{"__type":"Mywebservice+SampleClass","TaskId":"1","TaskName":"task1"},{"__type":"Mywebservice+SampleClass","TaskId":"2","TaskName":"task2"},{"__type":"Mywebservice+SampleClass","TaskId":"3","TaskName":"task3"},{"__type":"Mywebservice+SampleClass","TaskId":"4","TaskName":"task4"}]}

Despite no exceptions being thrown in the browser, I am perplexed as to why the grid is not binding with the data properly. It merely displays an empty grid with column headers and a paging toolbar. If anyone could shed light on what might be missing here, it would be greatly appreciated.

Please assist. Thank you!

Answer №1

Upon reviewing your store, I noticed that you have a proxy/reader defined - however, it seems like your model configuration is placed on the incorrect object.

model should actually be set on the store itself, rather than on the reader:

    var myStore = new Ext.data.Store(
        {
            autoLoad: true,
            model: 'myModel',
            proxy: new Ext.ux.AspWebAjaxProxy({
                url: '/ProjectManagement/Mywebservice.asmx/GetTasks',
                actionMethods: {
                    read: 'POST'
                },
                reader: {
                    type: 'json',
                    root: 'd'
                },
                headers: {
                    'Content-Type': 'application/json; charset=utf-8'
                }
            })
        });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can I create this chart in chart.js?

Can Chart.js be used to create a graph like the one in this image? https://i.sstatic.net/Ve7Vr.png ...

Filter through the array using the cast method

Trying to implement this: let selections = list.filter(obj => obj.type === "myType"); An issue arises with the filter function displaying an error message which states 'filter' does not exist on type 'NodeType' I attempted to ...

Guide to adding multiple new objects to Firebase using Python

I am trying to find a way to push JSON data to Firebase without having new keys generated for each object. Ideally, I would like to be able to define the key names myself. Below is the code I have been using : import pyrebase import json config = {my fi ...

Stopping a parent's event from firing when clicking on child elements without interfering with the child element events

Having read several posts such as this one, I am exploring a method to click on the parent div for it to hide, without hiding when clicking on either the search box or the 'click for event 2' text. I have tried using onclick stop propagation to ...

JavaScript for_each loop

Is there a way to access the field index of a JSON-Array when looping through it? I am aware that there is no foreach-loop like in PHP. This is an example of my json: { 'username': 'Karl', 'email': '<a href=" ...

What is the process for removing a row from the database in this scenario?

My current goal is to implement a functionality where clicking on the "Delete" button will remove a file from the server and also delete the corresponding database entry with the same file name. The file deletion process on the server works perfectly, but ...

Prevent JSON-Pretty from being cached for JavaScript files that rely on it

I recently created a Squarespace website using a template that features a unique masonry type gallery layout, which can be viewed at the following link: . Although I was drawn to this template specifically for its gallery design, I've encountered seve ...

`How can I use JavaScript to display a modal?`

I am currently a student immersing myself in the world of coding, particularly focusing on learning javascript/jquery. In my recent project, I have developed a chess game using RoR and now I am tackling the promotion move. The idea is that when a Pawn piec ...

Working with nested arrays of objects in Jsoncpp

Trying to navigate through a JSON file using the jsoncpp library has been quite the challenge for me. I am struggling with accessing the innermost array. Any helpful insights? { "key": int, "array1": [ { &quo ...

Looking to reduce the size of a logo image within a container as you scroll down a webpage?

I've been working on creating a logo section for my website, but I'm struggling to make it shrink as users scroll down and expand back to its original size when they scroll up. I've tried various JavaScript and jQuery functions without succe ...

Progressing begins before the task is finished

In my C# code written in VS2012 with WPF 4.5, I expected the .ContinueWith method to be executed after the task had completely finished. However, it seems like the continuation is starting on the await statement instead. This should have resulted in a val ...

Tips for storing dynamic data in an array using JavaScript

I'm trying to create a loop that will retrieve the href values from certain elements and store them in an array. Can someone help me with this? var linksArray = []; var elements = document.getElementsByClassName("title"); for (var i = 0; i < elem ...

Unable to update FB Login button to display "Logout" after user logs in to FB app

As a junior developer, I'm currently working on integrating Facebook login functionality into my React application following the quickstart guide provided by Facebook developers. However, I've encountered some issues with making the necessary mod ...

Tips for creating a visual map using a URL

Here is a code snippet that I found: https://openlayers.org/workshop/en/vector/geojson.html The code requires a URL to a countries.json file, like this: url: './data/countries.json' When I run the code, only zoom in and zoom out buttons appear ...

Adding a background image in javascript using data from a MySQL database

My current tech stack includes CodeIgniter, vanilla JavaScript, AJAX, CSS, and MySQL. I am trying to figure out how to set the background of an image that is stored in a MySQL database. While the following code is error-free and working perfectly, my cha ...

Retrieving information from relationships in Sequelize

In my Sequelize database, I have the following associations: db.checktypes.belongsToMany(db.questions, { through: db.checktypeslike, }); db.questions.belongsToMany(db.checktypes, { through: db.checktypeslike, }); Additionally, db.checktypeslike.hasMan ...

Steps to display a single entry in a Laravel/Vue implementation

My goal is to combine Laravel with Vue and eventually Nuxt in order to incorporate dynamic page transitions similar to the ones showcased on into my websites. I recently followed a tutorial on using Vue with Laravel at https://scotch.io/tutorials/build-a ...

Converting an HTML table into a multi-series chart

Is there a way to automatically convert an HTML table into a multi-series chart using JavaScript or jQuery? Here is a sample of my table: | Category | YYYY | YYYY | YYYY | | Asset | 1,500.00 | 3,590.00 | 5,000.00 | | Revenue | 2,560 ...

Enabling Context Isolation in Electron.js and Next.js with Nextron: A Step-by-Step Guide

I've been working on a desktop application using Nextron (Electron.js + Next.js). Attempting to activate context isolation from BrowserWindow parameters, I have utilized the following code: contextIsolation: true However, it seems that this doesn&ap ...

What is the process for attaching text or labels to an object, similar to applying decals?

Check out this website: On this site, you can create text, add it to objects like a decal, and then click "Ok" to confirm. Is there a way to make this effect visible on the design? Many thanks in advance! ...