Error ajax error-datatables warning: table id -example - c#

I click "ok" and in console error :
I'm new to programming and I need help. I need to use json to form a datatable from several data structures. At this point, I'm stuck on this error. Help please understand
The function in the controller is json.
[HttpGet]
public JsonResult Lowx()
{
var query = db.Infos.
Include(x => x.Profile).
Include(x => x.Cars).
ToList();
return Json(new { data = query });
}
table and ajax
<table class= "table" id="example" >
<thead>
<tr >
<th>first name</th>
<th>last name</th>
<th>middle name</th>
<th>birthday</th>
<th>carname</th>
<th>carnumber</th>
</tr>
</thead>
<tbody></tbody>
</table>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
<script src="~/Scripts/DataTables/jquery.dataTables.min.js"></script>
<script type="text/javascript">
$(document).ready(function (data) {
$("#example").DataTable({
ajax: {
url: '#Url.Action("Lowx")',
type: 'GET',
dataSrc: ""
},
columns: [
{ data: "FirstName", name: "FirstName" },
{ data: "LastName", name: "LastName" },
{ data: "MiddleName", name: "MiddleName" },
{ data: "BirthDate", name: "BirthDate" },
{ data: "CarName", name: "CarName" },
{ data: "CarNumber", name: "CarNumber" }
]
});
Console: Failed to load resource: the server responded with a status of 500 (Internal Server Error).
SCREENSHOTS FOR ALFRED AND ALL)
Screenshot copy-paste

Try copy-pasting this example in your view file. When it works fine, change the url to parse your own data and it should work. Note that the action is a POST, not a GET.
[HttpPost]
public JsonResult Lowx()
{
var query = db.Infos.Include(x => x.Profile).Include(x => x.Cars).ToList();
return Json(new { data = query });
}
http://jsfiddle.net/bababalcksheep/ntcwust8/
$(document).ready(function () {
var url = 'http://www.json-generator.com/api/json/get/cbEfqLwFaq?indent=2';
var table = $('#example').DataTable({
'processing': true,
'serverSide': true,
'ajax': {
'type': 'POST',
'url': url,
'data': function (d) {
return JSON.stringify( d );
}
}
});
$('#reload').click(function (e) {
table.ajax.reload();
});
$('.toggleCols').click(function (e) {
e.preventDefault();
var column = table.column( $(this).attr('data-column') );
column.visible( ! column.visible() );
});
});

Please declare the DataTable as follows:
$('#example').DataTable({
"ajax": {
"url": '#Url.Action("Lowx")',
"dataSrc": ""
},
"columns": [
{ "FirstName", "data.Profile.FirstName" },
{ "LastName", "data.Profile.LastName" },
{ "MiddleName", "data.Profile.MiddleName" },
{ "BirthDate", "data.Profile.BirthDate" },
{ "CarName", "data.Cars.CarName" },
{ "CarNumber", "data.Cars.CarNumber" }
]
});
In Chrome, look at the Network tab to see if the Ajax call was formed properly. In Visual Studio, put a Breakppoint at the beginning of Lowx() to see if you reach the code. Please share your findings.

Related

Json data is not showing in datatable using ASP.NET

I am using ASP.NET; I am getting the data from the backend as expected, but it is not showing in the web page using a datatable.
Web page:
#{
ViewBag.Title = "Employee";
}
<h2>Employee List</h2>
<table id="myTable">
<thead>
<tr>
<th>EmployeeId</th>
<th>Name</th>
<th>Age</th>
<th>Position</th>
</tr>
</thead>
</table>
JavaScript portion of code (jQuery)
$(document).ready(function () {
$('#myTable').DataTable({
processing:true,
"ajax": {
"url": "/Employee/GetList",
"type": "GET",
"dataType": "json",
"success": function (msg) {
console.log(msg.data);
},
"failure": function (response) {
alert(response);
},
"error": function (response) {
alert(response);
}
},
"columns": [
{ data: "EmployeeId" },
{ data: "Name" },
{ data: "Age" },
{ data: "Position"},
]
});
});
Here is the response I am getting from the backend. This is the data I copied from Netword -> Response tab against the endpoint I call to fetch the data
{
"data": [
{
"EmployeeId": 1,
"Name": "Dhruv",
"Age": 23,
"Position": "Full Stack Developer"
},
{
"EmployeeId": 2,
"Name": "Soni",
"Age": 21,
"Position": "DBA"
},
{
"EmployeeId": 3,
"Name": "Mike",
"Age": 24,
"Position": "Frontend Developer"
},
{
"EmployeeId": 4,
"Name": "Bob",
"Age": 20,
"Position":"SRE"
}
]
}
I am trying to get the data from database and show it to the user using a datatable. I am successfully getting the response back from the database, but the data is not showing inside the table. And I can't figure it out why....
Update:3
Controller:
public ActionResult GetList()
{
var empList = new List<Employee>()
{
new Employee(){ EmployeeId = 1, Name = "A", Age = 19, Position = "Engineer-I"},
new Employee(){ EmployeeId = 2, Name = "B", Age = 20, Position = "Engineer-II"},
new Employee(){ EmployeeId = 3, Name = "C", Age = 21, Position = "Engineer-I"},
new Employee(){ EmployeeId = 4, Name = "D", Age = 22, Position = "Engineer-III"},
};
return Json(new { data = empList }, JsonRequestBehavior.AllowGet);
}
Note: You even can directly return Json(new { empList }) in that case, in your HTML-Ajax you only have to write return msg; not msg.data
View:
<h2>Employee List</h2>
<table id="myTable">
<thead>
<tr>
<th>EmployeeId</th>
<th>Name</th>
<th>Age</th>
<th>Position</th>
</tr>
</thead>
</table>
#section scripts {
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function () {
$('#myTable').DataTable({
processing: true,
"ajax": {
"type": "GET",
"url": "/DatatableInAnotherWay/GetList",
"dataSrc": function (msg) {
console.log(msg.data);
return msg.data;
}
},
"columns": [
{ "data": "employeeId" },
{ "data": "name" },
{ "data": "age" },
{ "data": "position" },
]
});
});
</script>
}
Note: I am returning as return Json(new { data = empList }); so I would receive response as msg.data. Check the response in your browser console as below:
Importantly, be sure about the column case as you can see I am getting it as lower-case so I bind them as like this"data": "employeeId". As you are saying you are getting in Upper-Case as EmployeeId you should then bind as "data": "EmployeeId"
Final Output:
Special Note:
Remember these words forver, If you want to be a great programmer, you must concentrate on :
Debugging
Code readability
Self reading/teaching attitude
Update:2
If you still want to persist with your code: You could do as following:
$('#myTable').DataTable({
processing: true,
"ajax": {
"type": "GET",
"url": "/Employee/GetList",
"dataSrc": function (msg) {
return msg;
}
},
"columns": [
{ "data": "EmployeeId" },
{ "data": "Name" },
{ "data": "Age" },
{ "data": "Position" },
]
});
Issue on your code:
You were defining the column in worng way: you should do it in following way:
"columns": [
{ "data": "EmployeeId" },
{ "data": "Name" },
{ "data": "Age" },
{ "data": "Position" },
]
Update:2 Output:
Update:
Based on your updated question, its clearly seen that you are ajax calling pattern is incorrect. How your msg.data would be bounded into your "columns": no way. Please try my updated code. Just copy and paste.
I am successfully getting the response back from the database but the
data are not showing inside the table. And i can't figure it out why?
It's because of your row definition in your columns within the datatable.
You would define all of your data members in lower case - like
"columns": [
{ data: "employeeId" },
{ data: "name" },
{ data: "age" },
{ data: "position"},
]
Note: UpperCase EmployeeId, Name etc in jQuery datatable are causing parsing issues. In addition, please follow the $.ajax({}); calling format as per my demo for better code readability.
Complete example:
<table id="myTable" class="table table-striped table-bordered dt-responsive nowrap" width="100%" cellspacing="0">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
<th>Position</th>
</tr>
</thead>
</table>
#section scripts {
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function () {
$.ajax({
type: "GET",
url: "/Employee/GetList",
success: function (response) {
$('#myTable').DataTable({
data: response,
columns: [
{ data: 'EmployeeId' },
{ data: 'Name' },
{ data: 'Age' },
{ data: 'Position' }
]
});
},
error: function (response) {
alert(response.responseText);
}
});
});
</script>
}
Output:

DataTables error loading ajax source data

I am getting the following error when trying to load DataTables ajax sourced data:
DataTables warning: table id=report-table - Ajax error. For more information about this error, please see http://datatables.net/tn/7
Below is my DataTables html:
<table id="report-table" class="display nowrap" style="width:100%">
<thead>
<tr>
<th>Page ID</th>
<th>Schema</th>
<th>Name</th>
<th>Last Modified</th>
<th>Last Modified User</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Page ID</th>
<th>Schema</th>
<th>Name</th>
<th>Last Modified</th>
<th>Last Modified User</th>
</tr>
</tfoot>
</table>
Below is my DataTables javascript:
$('#report-table').DataTable({
"ajax": data,
"columns": [
{
"data": "PageId",
"orderable": true
},
{
"data": "SchemaName",
"orderable": false
},
{
"data": "Name",
"orderable": true
},
{
"data": "LastModified",
"orderable": true
},
{
"data": "LastModifiedUser",
"orderable": true
},
],
"order": [[3, "desc"]]
});
Below is the confirmed json my C# controller is returning for the DataTables ajax data:
{
"data":[
{
"PageId":"foo",
"SchemaName":"foo",
"Name":"foo",
"LastModified":"foo",
"LastModifiedUser":"foo"
},
{
"PageId":"foo",
"SchemaName":"foo",
"Name":"foo",
"LastModified":"foo",
"LastModifiedUser":"foo"
},
{
"PageId":"foo",
"SchemaName":"foo",
"Name":"foo",
"LastModified":"foo",
"LastModifiedUser":"foo"
}
]
}
The error seems to be related to the JSON format, but not sure what is wrong?
EDIT:
Adding full javascript code:
<script>
$(function () {
$("button#report-form-submit").click(function () {
event.preventDefault();
var data = $("form#report-form").serialize();
$.ajax({
type: "POST",
url: "#Url.Action("GetReportJson", "Report")",
data: data,
dataType: 'json',
beforeSend: function (data) {
},
success: function (data) {
// Report DataTables Init
// ===========================================
$('#report-table').DataTable({
"ajax": data,
"columns": [
{
"data": "PageId",
"orderable": true
},
{
"data": "SchemaName",
"orderable": false
},
{
"data": "Name",
"orderable": true
},
{
"data": "LastModified",
"orderable": true
},
{
"data": "LastModifiedUser",
"orderable": true
},
],
"order": [[3, "desc"]]
});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
},
complete: function (data) {
}
});
});
});
</script>
Your <script> block should look like this to initialize your data for your Data Tables:
<script>
$(function () {
$("button#report-form-submit").click(function () {
event.preventDefault();
var data = $("form#report-form").serialize();
$.ajax({
type: "POST",
url: "#Url.Action("GetReportJson", "Report")",
data: data,
dataType: "json",
method: "post",
beforeSend: function (data) {
},
success: function (data) {
// Report DataTables Init
// ===========================================
$('#report-table').DataTable({
"data":data,
"columns": [
{
"data": "PageId",
"orderable": true
},
{
"data": "SchemaName",
"orderable": false
},
{
"data": "Name",
"orderable": true
},
{
"data": "LastModified",
"orderable": true
},
{
"data": "LastModifiedUser",
"orderable": true
},
],
"order": [[3, "desc"]]
});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
},
complete: function (data) {
}
});
});
});
</script>
the data source should be an array of arrays that contains the data in the tbody
say
data = [
["foo","foo","foo","foo","foo"],
["foo","foo","foo","foo","foo"],
["foo","foo","foo","foo","foo"]
];
see the example [https://datatables.net/examples/data_sources/js_array.html][1]
additionally, use data: data.data instead of "ajax" : data
As your JSON response is an object but not an array, specify the ajax to get the JsonResponse.data as below:
"ajax": {
"url": /* Your Get Data API url */,
"dataSrc": function (json) {
return json.data;
},
},
OR
"ajax": {
"url": /* Your Get Data API url */,
"dataSrc": "data"
},
JQuery answer
Updated: Change from json.data to data as Post Owner changed requirement.
data: data
$.ajax({
type: "POST",
url: "#Url.Action("GetReportJson", "Report")",
data: data,
dataType: 'json',
beforeSend: function (data) {
},
success: function (data) {
// Report DataTables Init
// ===========================================
$('#report-table').DataTable({
"data": data,
... // Remaining DataTable configurations
});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
},
complete: function (data) {
}
});
Output
Reference
ajax - DataTables.net

How to call Ajax datatables with parameter ASP.NET MVC?

I want to send parameter when clicking a tag to controller but always null.
How can I get parameters when using datatable ajax? Please help me.
My code in controller:
public JsonResult Getdata(string isvk)
{
var orders = from o in db.Orders
select o;
if (isvk == null)
{
return Json(new { data = orders }, JsonRequestBehavior.AllowGet);
}
switch (isvk)
{
case "canceled":
orders = db.Orders.Where(o => o.Status == -1 || o.Status == -2);
break;
case "pending":
orders = db.Orders.Where(o => o.Status == 0);
break;
case "approved":
orders = db.Orders.Where(o => o.Status == 1);
break;
case "delivered":
orders = db.Orders.Where(o => o.Status == 2);
break;
default:
orders = db.Orders;
break;
}
return Json(new { data = orders.ToList() }, JsonRequestBehavior.AllowGet);
}
Tag <a> is outside the table:
peding
My Script:
var datatable = $("#myTable").DataTable({
ajax: {
type: "GET",
url: "#Url.Action("Getdata","Cart")",
},
columns: [
{ data: "CodeOrder"},
{ data: "FullName"},
{ data: "Email"},
{ data: "Phone" },
]
To send data from DataTables to the server (i.e. to your controller), you use the data option of the ajax function. So, first of all, add that:
ajax: {
type: "GET",
url: "#Url.Action("Getdata","Cart")",
data: function() {
return dataToSend;
}
},
You declare dataToSend as an empty JavaScript object at the start of the document.ready function:
var dataToSend = {};
Here is my simplified version of your <a> tag:
<a id="linkOne" linkData="pending" href="#">submit</a>
Following the dataToSend declaration, I added the following click handler for the <a> tag:
$("a#linkOne").on('click', function() {
event.preventDefault();
var linkDataValue = $( this ).attr( 'linkData' )
dataToSend = { "linkData": linkDataValue };
//console.log( dataToSend );
table.ajax.reload();
});
This code extracts the "pending" text from linkData="pending" in the <a> tag and adds it to the dataToSend object.
Finally, I trigger the DataTable ajax call using reload().
In the controller, this data will be received as a standard URL query parameter (because you are using GET):
linkData=pending
So you can access that in the usual way and format your response accordingly.
In your case, you need to replace my dataToSend logic with your required logic, for your specific <a> tag.
An important point here is that you need to create your dataToSend object correctly.
For one value, it is created as this, as in the above example:
{ "linkData": "pending" }
If you need to send multiple values (e.g. if you are processing a form) then you would build a JavaScript object like this:
[
{
"name": "fieldOne",
"value": "x"
},
{
"name": "fieldTwo",
"value": "y"
}
]
In this case, the object is an array of key-pair values.
For simple forms, the JavaScript serializeArray() function can assist with that - for example:
$( "#formOne" ).on( "submit", function( event ) {
event.preventDefault();
dataToSend = $( "#formOne" ).serializeArray();
//console.log( dataToSend );
table.ajax.reload();
});
UPDATE
In case it helps, here is the full HTML page for my test code.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Personnel</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">
<link rel="stylesheet" type="text/css" href="https://datatables.net/media/css/site-examples.css">
</head>
<body>
<div style="margin: 20px;">
<table id="example" class="display" style="width:100%">
<thead>
<tr>
<th>ID</th>
<th>First Name</th>
<th>Name</th>
<th>Phone</th>
</tr>
</thead>
</table>
<br>
<form id ="formOne">
<input id="fieldOne" type="text" name="fieldOne"></input>
<input id="fieldTwo" type="text" name="fieldTwo"></input>
<input type="submit" value="Submit">
</form>
<br>
<a id="linkOne" linkData="pending" href="#">submit</a>
</div>
<script type="text/javascript">
$(document).ready(function() {
var dataToSend = {};
$( "#formOne" ).on( "submit", function( event ) {
event.preventDefault();
dataToSend = $( "#formOne" ).serializeArray();
//console.log( dataToSend );
table.ajax.reload();
});
$("a#linkOne").on('click', function() {
event.preventDefault();
var linkDataValue = $( this ).attr( 'linkData' )
dataToSend = { linkData: linkDataValue };
//console.log( dataToSend );
table.ajax.reload();
});
var table = $('#example').DataTable( {
ajax: {
url: "http://localhost:7000/personnel",
method: "POST",
data: function( ) {
return dataToSend;
},
dataSrc: ''
},
"columns": [
{ "data": "id" },
{ "data": "firstname" },
{ "data": "name" },
{ "data": "phone" }
]
} );
} );
</script>
</body>
</html>
Welcome to StackOverflow!
You're already very close and the snippets you provided are helpful. What you're missing is that you want the data to update without leaving the page. Using an anchor tag the way you are will direct you to that page. Also, you controller action is returning a JsonResult, which won't return any type of view (but is correct in this case).
You need to add a page event that triggers on clicking the button and refreshes the data source.
There's a few approaches you can take for this, but here's one of them:
<button class="filter-datatable" data-url="#Url.Action("Index","Cart", new {isvk = "pending" })">
// pageScript.js
// jquery, initialization, etc...
$('.filter-datatable').on('click', function() {
var newSource = $(this).data('url');
datatable.ajax.url(newSource).load();
}
Update Script
$(document).ready(function () {
//test
var dataToSend = {};
$("a#linkOne").on('click', function () {
event.preventDefault();
var linkDataValue = $(this).data('id')
var linkurl = $(this).data('url')
dataToSend = { isvk: linkDataValue };
datatable.ajax.reload();
});
var datatable = $("#myTable").DataTable({
ajax: {
type: "GET",
url: "#Url.Action("Getdata","Cart")",
data: function () {
return dataToSend;
}
},
columns: [
{ data: "CodeOrder" },
{ data: "FullName" },
{ data: "Email" },
{ data: "Phone" },
],
});
});
tag <a>:
<a id="linkOne" data-id="pending" href="#">submit</a>

Memory leaks with change event that loads each time a new JQuery plugin DataTables

I have problems with memory leaks.
I display a table (with DataTables plugin) in my Html page following a select tag (Select2) that has an event change().
I noticed some memory leaks with the task manager (IE or FireFox).
My code works well, the only problem is memory leaks.
Here is my Html code, I have 2 tables, the second (table_statistic_10_ligne) is displayed when I click on one row of my first table (table_statistic_10), it displays the details of this row :
<body>
<select id="Select2" name="D1" style="margin-right :50px">
</select>
<script>
$("#Select2").change(function () { selectStat10(Select2.options[Select2.selectedIndex].value) });
</script>
<table id="table_statistic_10" class="display">
<caption class="caption">Detail van verkopen</caption>
<thead>
</thead>
<tbody>
</tbody>
</table>
<br />
<br />
<table id="table_statistic_10_ligne" class="display">
<thead>
</thead>
<tbody>
</tbody>
</table>
<script type="text/javascript">
fillSlectTagStat10();
</script>
</body>
Here is my javascript code, in the success, I retrieve the values (retrieved from a web service in C#) and I fill them in the datatables :
function getStatistic10(dstart, dend, nam) {
var response;
var allstat10 = [];
if (typeof myTabLigne10 != 'undefined') {
myTabLigne10.fnClearTable();
}
$.ajax({
type: 'GET',
url: 'http://localhost:52251/Service1.asmx/Statistic_10_Entete',
data: { "start": JSON.stringify(dstart), "end": JSON.stringify(dend), "name": JSON.stringify(nam) },
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
response = msg.d;
for (var i = 0; i < response.Items.length; i++) {
var j = 0;
allstat10[i] = [response.Items[i].Nom, response.Items[i].Date, response.Items[i].Piece, response.Items[i].Tiers, number_format(response.Items[i].AmoutHT, 2, ',', ' '), number_format(response.Items[i].AmountTTC, 2, ',', ' '), response.Items[i].Quantite];
}
if (typeof myTabEntete10 != 'undefined') {
myTabEntete10.fnClearTable();
}
fillDataTableEntete10(allstat10, dstart, dend);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("error loading statistic 10");
alert("Status: " + textStatus + "\n" + "Error: " + errorThrown);
}
});
}
Filling dataTables code :
function fillDataTableEntete10(data, dstart, dend) {
if ($("#table_statistic_10").css("visibility") == "hidden")
$("#table_statistic_10").css("visibility", "visible");
myTabEntete10 = $('#table_statistic_10').dataTable({
'aaData': data,
'aoColumns': [
{ "sTitle": "Nom" },
{ "sTitle": "Date" },
{ "sTitle": "Piece" },
{ "sTitle": "Tiers" },
{ "sTitle": "AmoutHT" },
{ "sTitle": "AmountTTC" },
{ "sTitle": "Quantite" }
],
"sPaginationType": "full_numbers",
"iDisplayLength": 10,
"bJQueryUI": true,
"bDestroy": true,
"bPaginate": true,
"bLengthChange": false,
"bFilter": true,
"bSort": false,
"bInfo": false,
"bAutoWidth": false,
"sDom": '<"top"f<"clear">>rt<"bottom"ilp<"clear">>'
});
I have approximately 10 values (customer) in the select tag (Select2). But one customer has about 20.000 rows that I fill in the datatables. And when I selected several times this customer, I see that the memory increases.
I used fnClearTable() but it doesn't work.
Have you an idea because I'm a little lost?
EDIT : I solved the problem, I updtate the DataTables with fnClearTable() and fnAddData(). But now, the problem is with my click event, I have memory leaks because of this code :
myTabEntete10.$('tr').bind('click',function () {
var data = myTabEntete10.fnGetData(this);
$('tr').removeClass('row_selected');
$(this).addClass('row_selected');
loadData10(dstart, dend, data[2], data[3]);
delete data;
});
Why?
I solved the problem.
I replace the DataTables in the existing.
if (typeof myTabEntete10 != 'undefined') {
$('body').off("click", '#table_statistic_10 tbody tr');
myTabEntete10.fnClearTable();
myTabEntete10.fnAddData(allstat10);
} else {
fillDataTableEntete10(allstat10, dstart, dend);
}
And I use the bDeferRenderoption of DataTables, see here.

How to bind ExtJS grid using Asp.net Websrvice?

I have tried all possible ways to get the JSON data from my webservice. I can see the JSON data in fiddler. Everything is fine except the data is not binding with the grid. here is my code.
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 which I get from server (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"}]}
I do not get any exception anywhere in browser. All seems perfect but still I do not understand why it is not binding the grid with data. It only shows an empty grid with column headers and paging tool bar.
Can anyone tell me what I am missing here?
Taking a look at your store, I see you have a proxy/reader defined - but your model config is on the wrong object.
model should be on the store - not the reader:
var storeData = 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'
}
})
});

Categories

Resources