I'm working with a C# MVC project and trying to use the DataTables plugin.
In trying to populate the table with test data I wind up getting an error at run-time that .dataTable is not a function.
It appears that I am including the js properly and I can see that the js loads in firebug. Hopefully someone can spot the error.
<body>
<div id="dynamic">
</div>
<script>
$(document).ready(function () {
function populateTable(json){
$('#dynamic').html('<table cellpadding="0" cellspacing="0" border="0" class="display" id="example"><thead></thead><tbody></tbody></table>');
$('#example').dataTable({
"aaData":[
["Trident","IE4.0","Win95",4,"X"]
],
"aoColumns": [
{"sTitle":"Engine"},
{"sTitle": "Browser" },
{"sTitle": "Platform" },
{"sTitle": "Version" , "sClass":"center" },
{"sTitle": "Grade" , "sClass": "center"}
]
});
};
function getCampaigns() {
$.ajax({
url : '/ADKTest/GetCampaigns',
}).done(function(response) {
populateTable(response);
alert("Worked");
}).error(function(jQXHR, textStatus, errorThrown) {
alert("Didn't Work");
});
};
getCampaigns();
});
</script>
Related
I'm trying to implement datatables to my MVC ASP.NET Core with MySql project so i followed a step-by-step tutorial but i can't fix this error:
" DataTables warning: table id=tblCustomers - Requested unknown parameter 'CustomerID' for row 0, column 0. For more information about this error, please see http://datatables.net/tn/4 "
Here's my HTML View page:
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<style type="text/css">
body {
font-family: Arial;
font-size: 10pt;
}
</style>
</head>
<body>
<div style="width: 500px">
<table id="tblCustomers" cellpadding="0" cellspacing="0" border="1" style="border-collapse:collapse">
<thead>
<tr>
<th>Customer Id</th>
<th>Name</th>
<th>City</th>
<th>Country</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
<link href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
$(function () {
$.ajax({
type: "POST",
url: "/Home/AjaxMethod",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
},
error: function (response) {
alert(response.d);
}
});
});
function OnSuccess(response) {
$("#tblCustomers").DataTable(
{
bLengthChange: true,
lengthMenu: [[5, 10, -1], [5, 10, "All"]],
bFilter: true,
bSort: true,
bPaginate: true,
data: response,
columns: [{ 'data': 'CustomerID' },
{ 'data': 'ContactName' },
{ 'data': 'City' },
{ 'data': 'Country' }]
});
};
</script>
</body>
</html>
and here is my Controller:
public class HomeController : Controller
{
private DBCtx Context { get; }
public HomeController(DBCtx _context)
{
this.Context = _context;
}
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult AjaxMethod()
{
var customers = Context.Customers.ToList();
return Json(JsonConvert.SerializeObject(customers));
}
}
My AjaxMethod is returning:
Newtonsoft.Json.JsonConvert.SerializeObject returned "[{"CustomerID":1,"ContactName":"Lucas","City":"Jundiai","Country":"Brasil"},{"CustomerID":2,"ContactName":"Vitoria","City":"Jundiai","Country":"Brasil"},{"CustomerID":3,"ContactName":"Soutto","City":"Jundiai","Country":"Brasil"}]" string
First you need to change your AjaxMethod to :
[HttpPost]
public IActionResult AjaxMethod()
{
var customers = Context.Customers.ToList();
return Json(customers);
}
Then in your OnSuccess function, change it to:
function OnSuccess(response) {
$("#tblCustomers").DataTable(
{
bLengthChange: true,
lengthMenu: [[5, 10, -1], [5, 10, "All"]],
bFilter: true,
bSort: true,
bPaginate: true,
data: response,
columns: [{ 'data': 'customerID' },
{ 'data': 'contactName' },
{ 'data': 'city' },
{ 'data': 'country' }]
});
The columns's first letter needs to be lowercase.
Test result:
I am new to datatables. I am trying to incorporate datatable into an existing ASP.NET MVC application. Below is my Index.cshtml page. I tried to incorporate datatable in this code:
<table id="BookAssignmentTable" class="table table-striped table-bordered" style="width:100%">
<thead>
<tr>
<th>Book</th>
<th>Office</th>
<th>Group</th>
<th>Updated By</th>
<th>Updated On</th>
</tr>
</thead>
</table>
<link href="https://cdn.datatables.net/1.10.21/css/dataTables.bootstrap.min.css" rel="stylesheet" />
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
#section scripts{
<script src="//cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/dataTables.bootstrap.min.js"></script>
<script>
var Popup, dataTable;
$(document).ready(function () {
dataTable = $("#BookAssignmentTable").DataTable({
"ajax": {
"url": "/BookAssign/GetData",
"type": "GET",
"datatype": "json"
},
"columns": [
{ "data": "Book" },
{ "data": "Office" },
{ "data": "Group" },
{ "data": "UpdatedBy" },
{ "data": "UpdatedOn" },
{
"data": "ID", "render": function (data) {
return "<a class='btn btn-default btn-sm' onclick=PopupForm('#Url.Action("StoreOrEdit", "bookAssignment_new")/" + data + "')><i class='fa fa-pencil'></i>Edit</a> <a class='btn btn-danger btn-sm' style='margin-left:5px' onclick=Delete(" + data + ")><i class='fa fa-trash'></i>Delete</a>";
},
"orderable": false,
"searchable": false,
"width" : "150px"
}
],
"language": {
"emptyTable" : "No data found please click on <b>Add New </b> Button"
}
});
});
function PopupForm(url) {
var formDiv = $('<div/>');
$.get(url)
.done(function (response) {
formDiv.html(response);
Popup = formDiv.dialog({
autoOpen : true,
resizable : false,
title : 'Fill Book Assignment Details',
height : 500,
width : 700,
close: function () {
Popup.dialog('destroy').remove();
}
});
});
}
</script>
Below is my BookAssignController:
public ActionResult GetData()
{
using (ACREmployeeEntities db= new ACREmployeeEntities())
{
List<bookAssignment_new> bookList = db.bookAssignment_new.ToList<bookAssignment_new>();
return Json(new { data = bookList }, JsonRequestBehavior.AllowGet);
}
}
This is in my route.config file:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "BookAssign", action = "Index", id = UrlParameter.Optional }
);
}
When I run my code, I see this URL, but I don't see any to data.
https://localhost:44374/BookAssign/Index
When I changed the url to
https://localhost:44374/BookAssign/getdata
the debugger stops at the getData method in the controller and returns the correct data. I am not sure what am I don't wrong and why I don't see any data.
Below is the screenshot:
For the first time appearance of .cshtml, you could do the following process:
First you should add <tbody></tbody> behind your <thead></thead> section.
In <tbody></tbody> section, you add a loop like this:
#for(var i = 0; i < yourData.ItsLength; i++)
{
<tr>
<td>yourData[i].YourFirstAttribute</td>
<td>yourData[i].YourSecondAttribute</td>
<td>yourData[i].YourThirdAttribute</td>
</tr>
}
P/S: I recommend you put your js script separately outside .cshtml file.
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: 'POST',
url: 'EmployeeService.asmx/GetEmployees',
dataType: 'json',
success: function (data) {
$('#datatable').dataTable({
data: data,
columns: [
{ 'data': 'Id' },
{ 'data': 'userID' },
{ 'data': 'userPassword' },
{ 'data': 'userEmail' },
{ 'data': 'userIsActiv' },
]
});
}
});
});
</script>
<body>
<form id="form1" runat="server" method="post">
<table id="datatable">
<thead>
<tr>
<th>Id</th>
<th>userID</th>
<th>userPassword</th>
<th>userEmail</th>
<th>userIsActiv</th>
</tr>
</thead>
</table>
<div>
</div>
</form>
</body>
I have a Jquery datatable which displays the data fetched from SQL database from Web service EmployeeService.asmx/GetEmployees.
I need to make this datatable to be editable like double click any column in any row, then I can edit the data like the datatable in the following link.
https://editor.datatables.net/examples/inline-editing/simple
How can I make the datatable editable like that so that after the editing the data will be updated correctly to the database?
I am trying to set an external input to search a jquery datatable. Please see my view code:
<link href="~/Content/DataTables/css/jquery.dataTables.min.css" rel="stylesheet"/>
<link href="~/Content/DataTables/css/select.bootstrap.css" rel="stylesheet"/>
<script src="~/Scripts/DataTables/jquery.dataTables.min.js"></script>
<script src="~/Scripts/DataTables/dataTables.select.min.js"></script>
<script type="text/javascript">
$(document)
.ready(function() {
var sfTable = $('#sfTable')
.dataTable({
"ajax": {
"url": "/Search/LoadData",
"type": "GET",
"datatype": "json"
},
"columns": [
{ "data": "Id", "autoWidth": true },
{ "data": "Name", "autoWidth": true },
{ "data": "Address", "autoWidth": true }
],
"searching": true,
"select": true
});
$('#searchMe')
.on('keyup',
function() {
sfTable.search(this.value).draw();
});
});
</script>
<input id="searchMe" type="text"/>
<table id="sfTable" class="table table-condensed">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Address</th>
</tr>
</thead>
</table>
If I use the default searching in the rendered datatable it works fine, but using my custom SearchMe control doesn't search the table. My final goal is to have two datatables which are searched from a single input.
Datatables - Search Box outside datatable
This led me to the answer, and it was really simple - the var sfTable = $('#sfTable').dataTable({ code had to be a capital D on DataTable() - suddenly it works!
I am trying to write some jquery code to retrieve a list of servers from a cloud account and display them in a table. When I load my page, my javascript executes and the proper JSON is returned, but when I try to use a jquery template to generate my html, I never get any output. Can anyone help me figure out where my problem is?
Javascript to fetch server data
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
url: '../../api/server/getservers',
type: 'POST',
success: function (result) {
$('#serverTemplate').tmpl(result).appendTo('#serverTable');
},
});
});
</script>
Jquery Template Javascript
<script id="serverTemplate" type="text/x-jQuery-tmpl">
{{each servers}}
<tr>
<td>${status}</td>
<td>${name}</td>
</tr>
{{/each}}
</script>
HTML
<table>
<thead>
<tr>
<th>Status</th>
<th>Server Name</th>
</tr>
</thead>
<tbody id="serverTable">
</tbody>
</table>
JSON Example
{
"servers": [
{
"progress": 100,
"id": 11111111,
"imageId": 1,
"flavorId": 1,
"status": "ACTIVE",
"name": "SERVER-1",
"hostId": "abcdefghijklmnopqrstuvwxyz",
"addresses": {
"public": [
"1.1.1.1"
],
"private": [
"2.2.2.2"
]
},
"metadata": {}
},
{
"progress": 100,
"id": 22222222,
"imageId": 2,
"flavorId": 2,
"status": "ACTIVE",
"name": "Server-2",
"hostId": "zxywufvslakdkdkdkdkdkdkdkdk",
"addresses": {
"public": [
"3.3.3.3"
],
"private": [
"4.4.4.4"
]
},
"metadata": {}
}
]
}
jQuery version 1.5.1
jQuery-tmpl
version beta 1
I solved the issue by changing the success function and adding an explicit parse of the JSON to an array.
var servers = jQuery.parseJSON(result);
$('#serverTemplate').tmpl(servers).appendTo('#serverTable');