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:
Related
I have the following code which implements a Jquery data table in a .net core application. However the bootstrap theme is not visible. This view implements a layout page. I have checked the console in browser for any errors and cannot find any.
<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/css" src="https://cdn.datatables.net/1.10.23/css/dataTables.bootstrap4.min.css"></script>
<script type="text/css" src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/css/bootstrap.css"></script>
<script type="text/css" src="https://cdn.datatables.net/fixedheader/3.1.7/css/fixedHeader.bootstrap4.min.css"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.8/js/jquery.dataTables.min.js">
</script>
<script>
$(function () {
$.ajax({
type: "POST",
url: "/ApplicationUsers/LoadData",
data: '{}',
contentType: "application/json; charset=utf-8",
headers: { 'Access-Control-Allow-Origin': '*' },
dataType: "json",
success: function (response) {
OnSuccess(response);
},
failure: function (response) {
alert(response.d);
},
error: function (response) {
alert(response.d);
}
});
});
// INITIALIZATION OF DATATABLES
// =======================================================
function OnSuccess(response) {
console.log(response);
$.noConflict();
$('#datatable').DataTable(
{
fixedHeader: true,
paging: true,
scrollX: false,
lengthChange: true,
searching: false,
ordering: true,
data: response.data.result,
columns: [
{ 'data': '', "defaultContent": "", },
{ 'data': 'userID', "defaultContent": "", },
{ 'data': 'name', "defaultContent": "", },
{ 'data': 'userName', "defaultContent": "", },
{ 'data': 'emailAddress', "defaultContent": "", }]
});
};
</script>
There are some errors in your code.
The type="text/css" should be in <link>, and you reference a incorrect dataTable css. Refer to the following code.
<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<link type="text/css" src="https://cdn.datatables.net/1.10.23/css/dataTables.bootstrap4.min.css"></link>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.8/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" />
Remove the ; at the end of the method OnSuccess.
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.
Hope that someone can help me with this.
this is my Controller
namespace PruebaBusquedaRun.Controllers
{
public class TestController : Controller
{
MandatosModel md = new MandatosModel();
// GET: Test
public ActionResult Index()
{
return View();
}
public ActionResult TestDataTable(string run)
{
List<MandatosModel> lmm = new List<MandatosModel>();
DataSet ds = new DataSet();
Int64 asd = Convert.ToInt64(run);
Conexion.ConexionOra conexora = new Conexion.ConexionOra();
ds = conexora.getMandatosPorRun(asd);
foreach (DataRow dr in ds.Tables[0].Rows)
{
lmm.Add(new MandatosModel
{
FOLIO = Convert.ToInt64(dr["FOLIO"]),
IDCAJA = Convert.ToInt64(dr["IDCAJA"]),
NOMBRES = dr["NOMBRES"].ToString(),
A_PATERNO = dr["A_PATERNO"].ToString(),
A_MATERNO = dr["A_MATERNO"].ToString(),
CORREO = dr["CORREO"].ToString()
});
}
return Json(new { data = lmm }, JsonRequestBehavior.AllowGet);
}
}
}
And Here is my View
<div style="width:90%; margin:0 auto;">
#using (Html.BeginForm("TestDataTable", "Test", FormMethod.Post))
{
<br />
<input type="text" id="run" name="run" required />
<button type="button" id="boton">Click Me!</button>
<input type="submit" name="asd" value="Buscar Mandatos" />
<br />
<br />
}
<table id="myTable">
<thead>
<tr>
<th>Folio</th>
<th>Nombres</th>
<th>Apellido Paterno</th>
<th>Apellido Materno</th>
<th>Correo</th>
</tr>
</thead>
</table>
</div>
<style>
tr.even {
background-color: #F5F5F5 !important;
}
</style>
#* Load datatable css *#
<!--<link href="//cdn.datatables.net/1.10.9/css/jquery.dataTables.min.css"
rel="stylesheet" />-->
<link href="~/Content/DataTable/jquery.dataTables.css" rel="stylesheet" />
#* Load datatable js *#
#section Scripts{
<!--<script src="//cdn.datatables.net/1.10.9/js/jquery.dataTables.min.js">
</script>-->
<script src="~/Scripts/DataTable/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function () {
$('#myTable').DataTable({
"ajax": {
"url": "/Test/TestDataTable",
"type": "GET",
"datatype": "json"
},
"columns": [
{ "data": "FOLIO", "autoWidth": true },
{ "data": "NOMBRES", "autoWidth": true },
{ "data": "A_PATERNO", "autoWidth": true },
{ "data": "A_MATERNO", "autoWidth": true },
{ "data": "CORREO", "autoWidth": true }
]
});
});
</script>
}
The main thing that i want to do is to pass a parameter to the TestDataTable method (run) and display the data in the DataTable, in the current state i'm able to execute my procedure and get all the data that i want, but after brings the data it does not return the view with the table, it returns only the plain data.
Sorry for the mistakes and my poor english.
Please help :(
i use a web api , i send my data like this
ajax: {
url: _json,
type: "GET"
},
so in your _json is url + parameters
/Test/TestDataTable?run=demo
--
you need i think is, ajax calling your controller
public JsonResult TestDataTable(string run)
{
try
{
//code
}
catch (Exception ex)
{
return Json(ex.Message);
}
}
some ajax like this.
$.ajax({
cache: !1,
url: '#Url.Action("TestDataTable", "TestController")',
async: !1,
data: { run: demo.val() },
success: function (e) { // data for datatables },
error: function (e, c, t) { alert(e.responseText) }
});
I have a page lets say Edit.cshtml in that page is a dropdownlist of item to updated. the loading of that page has no problem, the problem comes when I select an item on the dropdownlist and execute an ajax call.
$('#dDL').kendoDropDownList({
optionLabel: "Select",
dataTextField: "Value",
dataValueField: "Id",
dataSource: {
transport: {
read: '#Url.Action("GetItems", "BulkEdit")',
}
},
change: function (e) {
//this is where i call the '#Url.Action("GetMetaDataDetails", "BulkEdit")'
var test = getMetaDataDetails();
popupwindow.data("kendoWindow").open();
popupwindow.kendoWindow({
width: "600px",
title: "Mapping",
visible: false,
//modal: true,
animation: {
close: {
effects: "fade:out"
}
},
actions: [
"Pin",
"Minimize",
"Maximize",
"Close"
],
}).data("kendoWindow").center().open();
}
});
it goes through the controller with no issue, but it throws error if I return a view. Why?
this is my ajax call:
function getMetaDataDetails() {
return $.ajax({
type: "POST",
url: '#Url.Action("GetMetaDataDetails", "BulkEdit")',
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ itemTypeID: itemtypeID.toString() }),
dataType: "json",
success: function (data) {
debugger;
var checks = data;
},
error: function (data) {
debugger;
var check = data;
alert(result);
}
});
}
and this is my controller:
[HttpPost]
public virtual ActionResult GetMetaDataDetails(int itemTypeID)
{
var importProperties = GetImportColumnProperties(GetModel(itemTypeID));
var result = JsonConvert.SerializeObject(importProperties, Formatting.Indented,
new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
});
ViewData["MetaDataModel"] = importProperties;
return Json(result, JsonRequestBehavior.AllowGet);
}
This is the pop-up window that should be populated after executing the getMetaDataDetails(), itemMetaData should have the values return by getMetaDataDetails()
#(Html.Kendo().Window()
.Name("itemwindow")
.Title("Item Mapping")
//.Modal(true)
.Content(#<text>
<table class="table table-bordered">
<thead>
<tr>
<th>Table Column</th>
<th>Excel Column</th>
</tr>
</thead>
#foreach (var props in itemMetadata.GetType().GetProperties())
{
var label = props.GetCustomAttribute<CanBulkUpdateAttribute>().CanBulkUpdate;
if (label == true)
{
var disp = props.GetCustomAttributes<DisplayPropertyName>();
<tbody>
<tr>
<td class="col-sm-3">
<label>
#disp.First().DisplayName
</label>
</td>
<td class="col-sm-3">
<select kendoDropDownList name="" id="ddlitem_#props.Name" style="width :250px;"></select><br>
</td>
</tr>
</tbody>
}
}
</table>
<button id="uploadAll" onclick="updatetable()" class="btn btn-primary">Update</button>
</text>)
//.Width(420)
.Height(440)
.Visible(false)
)
I need to use the return of GetMetadataDetails as model for my "popupwindow"
Hope you can help me.
<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?