<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?
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.
Im binding my Data in View to Controller, so later I could do what I want with the data. In my View, im using dataTable and #Html.EditorForModel() to render my View.
View
<form action="xx" method="POST">
<table id="myTable" class="table table-bordered table-hover table-striped">
<thead>
<tr>
<th></th>
<th>
#Html.DisplayNameFor(model => model.Field1)
</th>
<th>
#Html.DisplayNameFor(model => model.Field2)
</th>
<th>
#Html.DisplayNameFor(model => model.Field3)
</th>
</tr>
</thead>
<tbody>
#if (Model != null)
{
#Html.EditorForModel()
}
</tbody>
<tfoot></tfoot>
</table>
<input type="submit" value="submit" />
</form>
Script
$("#myTable").dataTable({
searching: false,
ordering: false,
responsive: true,
"bLengthChange" : false,
"pageLength": 20,
"bStateSave": true
});
Controller
[HttpPost]
public ActionResult MyAction(List<MyModel> MyListModel)
This method works great if the data is no more than 1 page in dataTables. if its more than 1 page, then My Controller either only can receive the List Data of the first page or receive nothing(null)
How should I bind all of my data in DataTables from View to Controller? This binding should include all pages, not only the first one
I'm unsure how you're triggering the update of data, so assuming it's a button the following should work:
$('#your-button').on('click', function(e){
var data = ('#myTable').DataTable().$('input,select,textarea').serialize();
$.ajax({
url: '/MyController/MyAction/',
data: data,
success: function(){
alert('success');
},
error: function(){
alert('failure');
}
});
});
Edit 1:
As per this answer to How to post data for the whole table using jQuery DataTables, if you're set on using a form use the following:
var table = $('#myTable').DataTable();
$('#myForm').on('submit', function(e){
var form = this;
var params = table.$('input,select,textarea').serializeArray();
$.each(params, function(){
if(!$.contains(document, form[this.name])){
$(form).append(
$('<input>')
.attr('type', 'hidden')
.attr('name', this.name)
.val(this.value)
);
}
});
});
since you don't want any ajax
Use Javascript Source Data, Pass your model to the view, serialize it, and use it as your source
var myData = #Html.Raw(Json.Encode(Model.ListOfData));
//then pass it to the datatable
$('#example').DataTable( {
data: myData,
columns: [
{ title: "col1" },
{ title: "col2" },
etc ...
]
} );
With DataTables, only the current page data exist in the DOM. If you submit the form, only the current page data are being submitted back in the server. One solution to this is submit the data via ajax:
var myTable = $('#myTable').DataTable();
$('#your-form').on('submit', function(e){
e.preventDefault();
//serialize your data
var data = myTable.$('input,select,textarea').serialize();
$.ajax({
url: '#Url.Action('MyAction', 'MyController')',
data: data,
success: function(responseData){
//do whatever you want with the responseData
}
});
});
You need to use the data() method to get the data for the whole table:
$('#your-form').on('submit', function(e){
e.preventDefault();
var table = $('#myTable').DataTable();
var data = table.data();
$.ajax({
url: '/MyController/MyAction/',
type: 'POST',
dataType: 'json',
contentType: "application/json;",
data: JSON.stringify(data),
success: function(){
alert('success');
},
error: function(){
alert('failure');
}
});
Please go through following link
https://www.codeproject.com/Articles/155422/jQuery-DataTables-and-ASP-NET-MVC-Integration-Part
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'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>