Asp.net core Razor Page - JQ data table not load data - asp.net-core

I have an Asp.net core project with Razor Page ,I try to implement a JQ data table but the data not load.
Here is the Javascript code:
$('#dataList').DataTable({
// "iDisplayLength": 100,
// "sPaginationType": "full_numbers",
processing: true,
serverSide: true,
ajax: {
async: true,
type: "POST",
contentType: "application/json; charset=utf-8",
url: '/CoursesDP/?handler=Data',
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: function (d) {
// note: d is created by datatable, the structure of d is the same with DataTableParameters model above
// console.log(JSON.stringify(d));
return JSON.stringify(d);
},
success: function (r) {
console.log(r);
}
},
})
I write the data is coming to console:
{"draw":1,"recordsTotal":11,"recordsFiltered":11,"data":[["oooo"],["ccc"],["aaa"],["pppp"],["pppp"],["yyy"],["12"],["pppp"],["pppp"],["pppp"],["fff"]]}
This is the html code:
<table id="dataList" class="display" style="width:100%">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.CourseDP[0].CourseName)
</th>
</tr>
</thead>
but the data not load to the data table .
What can I do?

The following is a working sample using DataTables with testing data, you can refer to it.
CoursesDP.cshtml:
#page
#model ModelValidation_MVC_.Pages.CourseDB.CoursesDPModel
#{
ViewData["Title"] = "CoursesDP";
}
<h1>CourseDP</h1>
<div>
<table id="dataList" class="table table-striped table-bordered" style="width:100%">
<thead class="thead-dark">
<tr class="table-info">
<th>id</th>
<th>name</th>
<th>age</th>
<th>phone</th>
<th>email</th>
</tr>
</thead>
</table>
</div>
#section scripts{
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.js"></script>
<script type="text/javascript">
$('#dataList').DataTable({
"processing": true,
"serverSide": true,
ajax: {
type: "POST",
url: '/CourseDB/CoursesDP/?handler=Data',
},
columns: [
{ data: 'id' },
{ data: 'name' },
{ data: 'age' },
{ data: 'phone' },
{ data: 'email' }
]
})
</script>
}
CoursesDP.cshtml.cs:
[IgnoreAntiforgeryToken]
public class CoursesDPModel : PageModel
{
public static List<TestDT> testDTs = new List<TestDT> { new TestDT {id=1, name = "TestDT1", age = 1, phone = "1", email = "TestDT1#.com" },
new TestDT {id=2, name = "TestDT2", age = 2, phone = "2", email = "TestDT2#.com" }, new TestDT {id=3, name = "TestDT3", age = 3, phone = "3", email = "TestDT3#.com" } ,
new TestDT {id=4, name = "TestDT4", age = 4, phone = "4", email = "TestDT4#.com" }, new TestDT {id=5, name = "TestDT5", age = 5, phone = "5", email = "TestDT5#.com" } ,
new TestDT {id=6, name = "TestDT6", age = 6, phone = "6", email = "TestDT6#.com" },new TestDT {id=7, name = "TestDT7", age = 7, phone = "7", email = "TestDT7#.com" },};
public static List<TestId> testIds = new List<TestId> { new TestId { id = 1 }, new TestId { id = 2 } };
public IActionResult OnGet()
{
return Page();
}
public JsonResult OnPostData()
{
Postdata postdata = new Postdata { draw = 1, recordsTotal =7, recordsFiltered = 7, data = testDTs };
return new JsonResult(postdata);
}
}
result:

Related

My datatable is not picking the json result

I am using datatables and my get handler returns a json result but the datatable is not displaying it. What am I missing? Here's my code. I am using Visual Studio 2019 3.1 .net core with razor pages. I am trying to call my datatable in the OnGet handler. I tried the post but that did not work either.
My cust class:
public class Cust
{
public int Id { get; set; }
public string Name { get; set; }
public string PhoneNumber { get; set; }
public string Address { get; set; }
public string PostalCode { get; set; }
}
_layout.cshtml:
<div class="container">
<main role="main" class="pb-3">
#RenderBody()
</main>
</div>
<footer class="border-top footer text-muted">
<div class="container">
© 2022 - testApp - <a asp-area="" asp-page="/Privacy">Privacy</a>
</div>
</footer>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/dt-1.12.1/datatables.min.css" />
<script type="text/javascript" src="https://cdn.datatables.net/v/dt/dt-1.12.1/datatables.min.js"></script>
#RenderSection("Scripts", required: false)
My Index.cshtml.cs model code:
public class IndexModel : PageModel
{
[BindProperty]
public int Draw { get; set; }
// public IEnumerable<Column> Columns { get; set; }
// public IEnumerable<Order> Order { get; set; }
public int Start { get; set; }
public int Length { get; set; }
public List<Cust> Customers = new List<Cust>();
public JsonResult OnGet()
{
var recordsTotal = 3;
Cust cs1 = new Cust();
cs1.Id = 1;
cs1.Name = "test1";
cs1.Address = "address1";
cs1.PhoneNumber = "11111";
cs1.PostalCode = "1111";
Cust cs2 = new Cust();
cs2.Id = 1;
cs2.Name = "test2";
cs2.Address = "address1";
cs2.PhoneNumber = "11111";
cs2.PostalCode = "1111";
Cust cs3 = new Cust();
cs3.Id = 1;
cs3.Name = "test3";
cs3.Address = "address1";
cs3.PhoneNumber = "11111";
cs3.PostalCode = "1111";
Customers.Add(cs1);
Customers.Add(cs2);
Customers.Add(cs3);
var recordsFiltered = Customers.Count();
var data = Customers;
return new JsonResult(new
{
Draw = Draw,
RecordsTotal = recordsTotal,
RecordsFiltered = recordsFiltered,
Data = data
});
}
My Razor page -- Pages/customers/Index.cshtml:
#page
#model testApp.Pages.Customer.IndexModel
#{
}
<h1>Index</h1>
<p>
</p>
<table id="myTable" class="table">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.Customers[0].Id)
</th>
<th>
#Html.DisplayNameFor(model => model.Customers[0].Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Customers[0].PhoneNumber)
</th>
<th>
#Html.DisplayNameFor(model => model.Customers[0].Address)
</th>
<th>
#Html.DisplayNameFor(model => model.Customers[0].PostalCode)
</th>
<th></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
#section Scripts {
<script>
$(document).ready(function () {
$('#myTable').DataTable({
"processing": true,
"serverSide": true,
"ajax": {
url: "/customers/Index?handler=OnGet",
"type": "GET",
"dataType": "json"
},
"columns": [
{ "data": "id", "autowidth": true },
{ "data": "name", "autowidth": true },
{ "data": "phoneNumber", "autowidth": true },
{ "data": "address", "autowidth": true },
{ "data": "postalCode", "autowidth": true }
],
"order": [[0, "desc"]]
});
});
</script>
}
Here's my json response.
{
"draw": 0,
"recordsTotal": 3,
"recordsFiltered": 3,
"data": [
{
"id": 1,
"name": "test1",
"phoneNumber": "11111",
"address": "address1",
"postalCode": "1111"
},
{
"id": 1,
"name": "test2",
"phoneNumber": "11111",
"address": "address1",
"postalCode": "1111"
},
{
"id": 1,
"name": "test3",
"phoneNumber": "11111",
"address": "address1",
"postalCode": "1111"
}
]
}
I am just testing it with this project to see if I can get the datatable to work. I will be eventually getting the data from the database. Yes, the volume will be big, thousands of rows.
Here is a whole working demo you could follow:
Page(Pages/customers/Index.cshtml)
#page
#model IndexModel
<h1>Index</h1>
<p>
</p>
<table id="myTable" class="table">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.Customers[0].Id)
</th>
<th>
#Html.DisplayNameFor(model => model.Customers[0].Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Customers[0].PhoneNumber)
</th>
<th>
#Html.DisplayNameFor(model => model.Customers[0].Address)
</th>
<th>
#Html.DisplayNameFor(model => model.Customers[0].PostalCode)
</th>
<th></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
JS in page:
#section Scripts {
<script>
$(document).ready(function () {
$.ajax({
type: "GET",
url: "/customers/Index?handler=Json", //change here...
dataType: "json",
success: OnSuccess,
});
});
function OnSuccess(response) {
console.log(response.data)
$('#myTable').DataTable(
{
data: response.data,
columns: [
{ "data": "id" },
{ "data": "name" },
{ "data": "phoneNumber" },
{ "data": "address" },
{ "data": "postalCode" }
],
});
};
</script>
}
PageModel(Pages/customers/Index.cshtml.cs):
public class IndexModel : PageModel
{
[BindProperty]
public int Draw { get; set; }
// public IEnumerable<Column> Columns { get; set; }
// public IEnumerable<Order> Order { get; set; }
public int Start { get; set; }
public int Length { get; set; }
public List<Cust> Customers = new List<Cust>();
public void OnGet() //add this.....
{
}
public JsonResult OnGetJson() //change handler name..
{
var recordsTotal = 3;
Cust cs1 = new Cust();
cs1.Id = 1;
cs1.Name = "test1";
cs1.Address = "address1";
cs1.PhoneNumber = "11111";
cs1.PostalCode = "1111";
Cust cs2 = new Cust();
cs2.Id = 1;
cs2.Name = "test2";
cs2.Address = "address1";
cs2.PhoneNumber = "11111";
cs2.PostalCode = "1111";
Cust cs3 = new Cust();
cs3.Id = 1;
cs3.Name = "test3";
cs3.Address = "address1";
cs3.PhoneNumber = "11111";
cs3.PostalCode = "1111";
Customers.Add(cs1);
Customers.Add(cs2);
Customers.Add(cs3);
var recordsFiltered = Customers.Count();
var data = Customers;
return new JsonResult(new
{
Draw = Draw,
RecordsTotal = recordsTotal,
RecordsFiltered = recordsFiltered,
Data = data
});
}
}
_Layout.cshtml:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>#ViewData["Title"] - RazorPagesProj3_1</title>
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="~/css/site.css" />
</head>
<body>
<header>
//....
</header>
<div class="container">
<main role="main" class="pb-3">
#RenderBody()
</main>
</div>
<footer class="border-top footer text-muted">
<div class="container">
© 2022 - RazorPagesProj3_1 - <a asp-area="" asp-page="/Privacy">Privacy</a>
</div>
</footer>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="~/js/site.js" asp-append-version="true"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/dt-1.12.1/datatables.min.css" />
<script type="text/javascript" src="https://cdn.datatables.net/v/dt/dt-1.12.1/datatables.min.js"></script>
#RenderSection("Scripts", required: false)
</body>
</html>

vue js error:" For recursive components, make sure to provide the "name" option." when recursively create table

I create a dynamic HTML table by vue js which get data from server. The data includes 'columns', which is a Array with server objects including the table header(key is title), 'q', is the value type of each column generated from database table column name, 'content", the value display method. e.g content='content":'', the cell will display like ''.
HTML Part
<div id="app3">
<table class="table table-bordered">
<thead>
<tr>
<th scope="col" v-for="c in columns" v-text="c.title"></th>
</tr>
</thead>
<tbody>
<vue-cell:rows="rows" :columns="columns">
</vue-row>
</tbody>
</table>
</div>
Vue js part
<script>
var columns =[
{'q': "id",
'title': 'id',
'content":'<input type="checkbox">'
},
{'q': "type",
'title': 'Type',
'content":''
},
]
var rows=[
{'id': 1,
'type':"Server",
},
{'id': 2,
'type':"PC",
},
]
create component to loop rows and column
Vue.component('vue-cell', {
name:'inputBox',
props: {
rows: Array,
columns: Array,
},
render: function (createElement) {
var self = this
return createElement('tr', self.rows.map(function(row) {
return createElement('td', self.columns.map(function(column) {
// comlum.q = id or type ...
// column['content'] = <input type="checkbox">
//assign row.id as defalut value
if (column['content'].includes('checkbox')) {
return createElement('input', {
attrs: {
type: "checkbox",
},
domProps: {
// column.q may not be 'id' maybe type
// get the value of type or id in a row.
value: row[column.q],
}
})
} else {
return row[column.q];}
}))
}))
},
})
Create a new Vue
new Vue ({
data: function() {
return {
columns: [],
rows:[],
}
},
created: function() {
var self = this;
axios.("/web/asset-json.html").then(function (response) {
self.columns = [...response.data.columns];
self.rows = [...response.data.rows]
})
}
})
</script>

jquery datatable does not get initialized with given response

I want to initialize data table with my generated response
my response looks like this
{data: Array(3), status: true}
data : Array(3)
0 : {countryId: 1, countryName: "sampleCountry", countryShortCode: "sampleCode", status: "yes"}
1 : {countryId: 2, countryName: "pakistan", countryShortCode: "pak", status: "yes"}
2 : {countryId: 3, countryName: "sample2", countryShortCode: "pak", status: "yes"}
please look at my html
<table class="table table-striped" id="countryTable">
<thead>
<tr>
<th>S.NO.</th>
<th>Country Name</th>
<th>Country Short Name</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
please look at my datatable initialization
$.ajax({
url : url,
type:"get",
contentType:'application/json; charset=utf-8',
dataType: 'json' ,
async: false,
success:function(response)
{
alert(response.data);
$('#countryTable').DataTable( {
"fnRowCallback" : function(nRow, aData, iDisplayIndex){
$("td:first", nRow).html(iDisplayIndex +1);
return nRow;
},
destroy: true,
mydata: response.data,
columns: [
{ mydata:'countryId'},
{ mydata:'countryName'},
{ mydata:'countryShortCode'}
]
} );
console.log(response);
}
});
after initialization data table shows as No data available in table but table gets initialized with datatable plugin .
data is not coming into table.
what went wrong in my code please help me.
The code looks fine, you just need to change mydata to data, like this:
var response = {
data: [{
countryId: 1,
countryName: "sampleCountry",
countryShortCode: "sampleCode",
status: "yes"
},
{
countryId: 2,
countryName: "pakistan",
countryShortCode: "pak",
status: "yes"
},
{
countryId: 3,
countryName: "sample2",
countryShortCode: "pak",
status: "yes"
}
],
status: true
}
$('#countryTable').DataTable({
"fnRowCallback": function(nRow, aData, iDisplayIndex) {
$("td:first", nRow).html(iDisplayIndex + 1);
return nRow;
},
destroy: true,
data: response.data,
columns: [{
data: 'countryId'
},
{
data: 'countryName'
},
{
data: 'countryShortCode'
}
]
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet" />
<table class="table table-striped" id="countryTable">
<thead>
<tr>
<th>S.NO.</th>
<th>Country Name</th>
<th>Country Short Name</th>
</tr>
</thead>
<tbody>
</tbody>
</table>

Knockout select values from controller

I get respons from controller
[HttpGet]
public JsonResult GetItems(string date)
{
IList<dough> modelList = new List<dough>();
modelList.Add(new dough { Type = "framed" });
modelList.Add(new dough { Type = "unframed" });
modelList.Add(new dough { Type = "soft" });
return Json(modelList, JsonRequestBehavior.AllowGet);
}
and display it in such way
<table>
<thead>
<tr><th>Waste</th></tr>
</thead>
<tbody data-bind="foreach: items">
<tr>
<td><select data-bind="options: $root.availableWastes, value: Waste, optionsText: 'Type'"></select></td>
</tr>
</tbody>
</table>
result
The main question is how to display items with default values that was getted from controller? What need to fix?
Controller:
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
return View();
}
[HttpGet]
public JsonResult GetItems(string date)
{
IList<dough> modelList = new List<dough>();
modelList.Add(new dough { Type = "framed" });
modelList.Add(new dough { Type = "unframed" });
modelList.Add(new dough { Type = "soft" });
return Json(modelList, JsonRequestBehavior.AllowGet);
}
}
class dough
{
public string Type { get; set; }
}
Index.cshtml
#{
ViewBag.Title = "Index";
}
<script src="~/Scripts/knockout-2.2.0.js"></script>
<button data-bind="click: loadItems">Load</button>
<table>
<thead>
<tr><th>Waste</th></tr>
</thead>
<tbody data-bind="foreach: items">
<tr>
<td><select data-bind="options: $root.availableWastes, value: Waste, optionsText: 'Type'"></select></td>
</tr>
</tbody>
</table>
<script>
function MyViewModel() {
var self = this;
self.availableWastes = [{ Type: "framed", score: 0 },
{ Type: "soft", score: 1 },
{ Type: "unframed", score: 2 }];
self.items = ko.observableArray();
var date = new Date();
self.loadItems = function () {
var date = new Date();
debugger;
$.ajax({
cache: false,
type: "GET",
url: "Home/GetItems",
data: { "date": date },
success: function (data) {
var result = "";
self.items.removeAll();
$.each(data, function (id, item) {
self.items.push({ Waste: item.Type });
});
},
error: function (response) {
alert('eror');
}
});
}
}
ko.applyBindings(new MyViewModel());
</script>
Looks like you want to pre-select values.
Update self.items with the Type name and Waste into an observable:
self.items.push({ Waste: ko.observable(item.Type), Type: item.Type });
Then use that in the optionsValue binding:
<select data-bind="options: $root.availableWastes, value: Waste, optionsText: 'Type', optionsValue: 'Type'">
Screenshot:

paging using knockout js

At first I have displlay data using knockout js successful,here is my code:
Js
var viewMode = {
lookupCollection: ko.observableArray()
};
$(document).ready(function () {
$.ajax({
type: "GET",
url: "/Home/GetIndex",
}).done(function (data) {
$(data).each(function (index, element) {
viewModel.lookupCollection.push(element);
});
ko.applyBindings(viewMode);
}).error(function (ex) {
alert("Error");
});
});
View:
<table class="paginated">
<tr>
<th>
Name
</th>
<th>
Price
</th>
<th>
Category
</th>
<th></th>
</tr>
<tbody data-bind="foreach: lookupCollection">
<tr>
<td data-bind="text: Name"></td>
<td data-bind="text: price"></td>
<td data-bind="text: Category"></td>
<td>
<button class="btn btn-success">Edit</button>
<button class="btn btn-danger">Delete</button>
</td>
</tr>
</tbody>
</table>
However, I need more code to paging the list items, I follow this site http://knockoutjs.com/examples/grid.html and replay my code but It has not display my list items:
JS:
var initialData = {
lookupCollection: ko.observableArray()
};
var PagedGridModel = function (items) {
this.items = ko.observableArray(items);
this.sortByName = function () {
this.items.sort(function (a, b) {
return a.name < b.name ? -1 : 1;
});
};
this.jumpToFirstPage = function () {
this.gridViewModel.currentPageIndex(0);
};
this.gridViewModel = new ko.simpleGrid.viewModel({
data: this.items,
columns: [
{ headerText: "Name", rowText: "Name" },
{ headerText: "Category", rowText: "Category" },
{ headerText: "Price", rowText: function (item) { return "$" + item.price.toFixed(2) } }
],
pageSize: 4
});
};
$(document).ready(function () {
$.ajax({
type: "GET",
url: "/Home/GetIndex",
}).done(function (data) {
$(data).each(function (index, element) {
viewModel.lookupCollection.push(element);
});
ko.applyBindings(new PagedGridModel(initialData));
}).error(function (ex) {
alert("Error");
});
});
View:
<div data-bind='simpleGrid: gridViewModel'> </div>
<button data-bind='click: sortByName'>
Sort by name
</button>
<button data-bind='click: jumpToFirstPage, enable: gridViewModel.currentPageIndex'>
Jump to first page
</button>
thankyou very much your answer:
The "simpleGrid" binding u try to use is a custom one, not available by default in knockout.
Here's a simple example for pagination using a computed observable :
Fiddle : http://jsfiddle.net/RapTorS/qLHwx/
var viewModel = function () {
var self = this;
self.pageSize = 4;
self.currentPage = ko.observable(1);
self.lookupCollection = ko.observableArray([]);
self.currentCollection = ko.computed(function () {
var startIndex = self.pageSize * (self.currentPage() - 1);
var endIndex = startIndex + self.pageSize;
return self.lookupCollection().slice(startIndex, endIndex);
});
};