Use extjs gridpanel to obtain, bind, and display data from Web Service

Source: Internet
Author: User
This article describes how to use the gridpanel component of extjs to obtain XML data from ASP. NET web service and bind and display it.

The gridpanel component can receive multiple data formats when binding data. JSON and XML are the most common examples. If you want to bind the gridpanel with JSON data (this is also a "common" and "popular" solution on the Internet), you need to modify the web of the web service. set config to change the output data format to JSON (XML by default. For the setting method, see the http://www.cnblogs.com/regedit/archive/2008/03/04/1089948.html article ).

I personally think this method is too cumbersome. To ensure that the existing web service is not significantly adjusted, I decided to continue to let it return XML format data. Therefore, you must bind gridpanel data in XML format. That is to say, we need to use Ext. Data. xmlreader instead of Ext. Data. jsonreader when binding data. The specific implementation method is as follows:

1. Web Service Section:

Using system;
Using system. Web;
Using system. collections;
Using system. Web. Services;
Using system. Web. Services. Protocols;
Using system. configuration;
Using system. Data;
Using system. Data. sqlclient;

[WebService (namespace = "http://tempuri.org/")]
[Webservicebinding (conformsto = wsiprofiles. basicprofile1_1)]
Public class articleservice: system. Web. Services. WebService {

// SQL connection string
Private readonly string _ strconn = configurationmanager. connectionstrings ["junchieh"]. connectionstring;

// Limit rows starting from start, sorted by sort field, sorted by Dir (incoming "ASC" or "DESC ")
[Webmethod]
Public dataset getarticles (INT start, int limit, string sort, string DIR)
{
Dataset DS = new dataset ("article ");

// Obtain data from the database and put it into the record table
String strsql = string. Format (
"Select top {0} * from article where id not in (select top {1} ID from article order by {2} {3 }) order by {2} {3 }",
Limit, start, sort, DIR );
Sqldataadapter da = new sqldataadapter (strsql, _ strconn );
Datatable dtrecord = new datatable ("record ");
Lock (DA)
{
Da. Fill (dtrecord );
}
DS. Tables. Add (dtrecord );

// Calculate the total number of rows and put them into the results table.
Datatable dtresult = new datatable ("Results ");
Dtresult. Columns. Add ("totalrecords ");
Datarow DR = dtresult. newrow ();
Using (sqlconnection conn = new sqlconnection (_ strconn ))
Using (sqlcommand cmd = new sqlcommand ("select count (*) from article", Conn ))
{
Try
{
Conn. open ();
Dr ["totalrecords"] = (INT) cmd. executescalar ();
}
Catch
{
// Do nothing
}
}
Dtresult. Rows. Add (DR );
DS. Tables. Add (dtresult );

Return Ds;
}
}

Getaritcles returns a dataset. It contains two datatables. The first one stores the data on the current page (specified by the start and limit parameters), and the other stores the number of rows of all data in the database, used by the gridpanel component of the client. Client part (excerpt ):

<SCRIPT type = "text/JavaScript">
Ext. onready (function (){
// Column
VaR CM = new Ext. Grid. columnmodel ([
{Header: 'id', dataindex: 'id', sortable: True, width: 10 },
{Header: 'title', dataindex: 'title', sortable: true },
{Header: 'date', dataindex: 'date', sortable: True, width: 50, Renderer: renderdate} // format it in the renderdate Function
]);

// Data Source
VaR store = new Ext. Data. Store ({
URL: 'services/articleservice. asmx/getarticles ', // web service address
Reader: New Ext. Data. xmlreader (
{
Totalrecords: 'totalrecords ', // The total number of data rows. Corresponding to the totalrecores column of the results table in the dataset returned by getarticles
Record: 'record ', // data. Corresponding to the record table in the dataset returned by getarticles
ID: 'id' // primary key. ID column of the record table in the dataset returned by getarticles
},
[
{Name: 'id '},
{Name: 'title '},
{Name: 'date '}
]
),
Remotesort: True // server order
});
Store. setdefaultsort ('date', 'desc'); // sort by date column in descending order by default

// Pagination bar
VaR bbar = new Ext. pagingtoolbar (
{
Pagesize: 4,
Store: store,
Displayinfo: True,
Displaymsg: 'currently {0}-{1} items are displayed, total {2} items ',
Emptymsg: "No data"
}
);

// Gridpanel component
VaR grid = new Ext. Grid. gridpanel ({
Frame: True,
Enablehdmenu: false,
Width: 600,
Height: 300,
Title: 'Article list ',
Loadmask: {MSG: 'loading data. Please wait ...... '},
El: 'grid ',
Store: store,
CM: cm,
Bbar: bbar,
Viewconfig :{
Forcefit: True
}
});
Grid. Render ();
Store. Load ({Params: {start: 0, limit: 4}); // page 1st is displayed at the beginning, with 4 data entries per page.
});

// Format the date
// Format the original date data (for example, 2008-04-07t14: 39: 41.02 + 08: 00) in the XML data to a readable date (for example, 14:39:41)
Function renderdate (value)
{
VaR redate =/"d {4}"-"d {2}"-"d {2}/GI;
VaR retime =/"d {2}:" d {2}: "d {2}/GI;
Return Value. Match (redate) + "" + value. Match (retime );
}
</SCRIPT>

<! -- Display position of the gridpanel component -->
<Div id = "Grid" style = "height: 300px; margin: auto;"> </div>

XML data is returned from the getarticles method in the Web service. When binding data to the Ext. Data. Store component, use Ext. Data. xmlreader instead of the Ext. Data. jsonreader that is frequently seen on the Internet. When binding, We need to "tell" which nodes of xmlreader represent data entries in XML data (in this example, "record") and which node represents the total number of data entries (in this example, "totalrecords "), and the primary key node of the data (in this example, "ID "). You can understand the data binding process of xmlreader:

In addition, we can see from the XML data in that the date format is "ugly". If it is not modified, it will be displayed in the customer's gridpanel component as it is. Therefore, you need to process the date data before the client displays the data. Specify Renderer for the date column when Ext. Grid. columnmodel is created (note the bold part ):

{Header: 'date', dataindex: 'date', sortable: True, width: 50, Renderer: renderdate}

The "renderdate" in the Code is a JavaScript function, which is defined as follows:

Function renderdate (value)
{
VaR redate =/"d {4}"-"d {2}"-"d {2}/GI;
VaR retime =/"d {2}:" d {2}: "d {2}/GI;
Return Value. Match (redate) + "" + value. Match (retime );
}

The value parameter in this function is the original date data, which is passed in by Ext. Grid. columnmodel. Use a regular expression in the function to extract the "date" and "time" sections of the date data, and then splice them and return them.

The running interface after the entire program is executed is shown in:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.