Issue populating data in jquery datatable - javascript

This is my /Books/userHome view:
#model CSBSTest.Models.tbl_Book
#{
ViewBag.Title = "UserHome";
Layout = "~/Views/Shared/_Profile.cshtml";
}
<h2>Books for sale by CUST Students</h2>
<br />
<br />
<table id="books" class="table table-bordered table-hover">
<thead>
<tr>
<th>Id</th>
<th>Book Name</th>
<th>Author</th>
<th>Version</th>
</tr>
</thead>
<tbody></tbody>
</table>
#section scripts
{
<script>
$(document).ready( function () {
var dataTable = $("#books").DataTable({
ajax: {
url: "/Book/GetBooks",
dataSrc: ""
},
columns: [
{
data:"Id"
},
{
data: "Name"
},
{
data: "Author"
},
{
data: "Version"
}
]
});
});
</script>
}
I am calling /Books/GetBooks as below:
public ActionResult UserHome()
{
return View();
}
public ActionResult GetBooks()
{
var list = _context.tbl_Book.ToList();
return Json(list, JsonRequestBehavior.AllowGet);
}
The GetBooks returns json result which is called from UserHome scripts section as shown above, I want to populate the list returned by /Books/GetBooks into jquery datatable but its gives the following exception:
.
any help will be highly appreciated thanks in advance.

var list = _context.tbl_Book.ToList();
Here "list" is database table object and you should not return it directly.
Use user defined model and than return it
public class customModel{
//properties
}
var list = _context.tbl_Book.ToList();
List<custommodel> test = list.select(a=>new custommodel{
//assingn properties
});
return Json(test , JsonRequestBehavior.AllowGet);

Related

Set Query Results as Source for DataTable

I am trying to set the source of my datatable to the data returned from my stored procedure. This is my code, but my DataTable is not populated. Can someone please assist me with updating this code so the DataTable is populated with the stored procedure results?
This is my JavaScript
$("#btnClick").click(function () {
$('#example').DataTable({
ajax: {
url: getURL,
method: "GET"
},
columns: [
{ data: "Location" },
{ data: "TC" }
]
});
});
This is my HTML
<div id="table1">
<table id="example" class="display">
</table>
</div>
<br />
<div class="text-center">
<div class="btn-group">
<button type="button" id="btnClick">Button One</button>
</div>
</div>
#section Scripts {
<script>
var getURL = '#Url.Action("GTC")';
</script>
}
This is my Controller Code:
[ApiController]
[Route("api/EmpCheck")]
public class EmpCheckController : Controller
{
EmpCheck _context;
public EmpCheckController( context)
{
_context = context;
}
public IActionResult Index()
{
var VerifyAllEmpsOnDuty = _context.EmpCheckModel.FromSql("_GetClockedInEmps").ToList();
return View(VerifyAllEmpsOnDuty);
}
}
You can directly bind ajax source to datatable. if your API is working fine.
you can do it by two way.
1- directly bind ajax source.
2- fetch record using ajax and then bind response to DataTable.
Here is working example for both
Please check this one For more details Click here
cshtml page
<div id="table1">
<table id="example" class="display">
</table>
</div>
<br />
<div class="text-center">
<div class="btn-group">
<button type="button" id="btnClick">Button One</button>
</div>
</div>
Controller Code
[ApiController]
[Route("api/EmpCheck")]
public class EmpCheckController : Controller
{
EmpCheck _context;
public EmpCheckController( context)
{
_context = context;
}
public IActionResult Index()
{
return View();
}
public IActionResult LoadDataTable()
{
var VerifyAllEmpsOnDuty = _context.EmpCheckModel.FromSql("_GetClockedInEmps").ToList();
return Json(new
{
recordsTotal = VerifyAllEmpsOnDuty.Count(),
data = VerifyAllEmpsOnDuty
}, JsonRequestBehavior.AllowGet);
}
}
Javascript code
#section Scripts {
<script>
$( document ).ready(function() {
console.log( "ready!" );
var getURL = '#Url.Action("LoadDataTable","EmpCheck")';
This is my JavaScript
$("#btnClick").click(function () {
$('#example').DataTable({
ajax: {
url: getURL,
method: "GET"
},
columns: [
{ data: "Location" },
{ data: "TC" }
]
});
});
});
</script>
}

jquery Datatables and css not rendering in mvc 4

I have a simple view page, trying to render jquery datable for my view in MVC4.
My view [Admin.cshtml]
<div style="width:90%; margin:0 auto;">
<table id="myTable">
<thead>
<tr>
<th>Practice Name</th>
<th>Practice Address</th>
<th>Practice Email</th>
<th>Practice Telephone</th>
<th>Created Date</th>
</tr>
</thead>
</table>
</div>
and my reference to css and js for jquery datatables are underneath the section:
<link type="text/css" href="//cdn.datatables.net/1.10.9/css/jQuery.dataTables.min.css" rel="stylesheet"/>
#section Scripts{
<script type="text/javascript" src="//cdn.datatables.net/1.10.9/js/jQuery.dataTables.min.js"></script>
<script>
$(document).ready(function () {
$('#myTable').dataTable({
"ajax": {
"url": "/Home/Admin",
"type": "GET",
"datatype": "json"
},
"columns": [
{ "data": "Practice_Name", "autowidth": true },
{ "data": "Practice_Address", "autowidth": true },
{ "data": "Practice_Email", "autowidth": true },
{ "data": "Practice_Telephone", "autowidth": true },
{ "data": "Created_Date", "autowidth": true }
]
});
});
</script>
}
and in my Controller, i have a simple GET section:
public ActionResult Admin()
{
var data = db.Practices.ToList();
return Json(new { data = data }, JsonRequestBehavior.AllowGet);
}
But, when i run this application, i am getting my resultset like this
Where am i going wrong ?
Change your controller method name:
public ActionResult Admin() to public ActionResult GetAdminData()
Create another action method:
[Authorize]
public ActionResult Admin () => View();
Modify your JavaScript code:
"url": "/Home/Admin" to "url": "/Home/GetAdminData"
And update CDN links because they are too old:
https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css
https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js
Why is all of this needed?
When you navigate to /Home/Admin your return View (the Admin.cshtml)
Your view contains some custom JavaScript logic which will try to fetch a list of items from the database (your GetAdminData method)
GetAdminData returns JSON which can be used by DataTables in order to show your desired content on the page.

I want to show table data using Ajax in Asp.Net MVC. What is wrong with this Ajax syntax?

I want to show table data using Ajax request.
Here is my Ajax Syntax:
$(document).ready(function() {
var table = $("#attendance").DataTable({
ajax: {
url: '#Url.Action("GetAttendance", new {id = Model.Student.Id})',
dataSrc: ""
},
columns: [
{
data: "Date",
render: function(data) {
return data;
}
},
{
data: "Status.StudentStatus",
render: function(data) {
return data;
}
}
]
});
Here is my action method:
public JsonResult GetAttendance(int id)
{
var studentAttendance = _context.Attendances.ToList().Where(m => m.StudentId == id);
return Json(studentAttendance, JsonRequestBehavior.AllowGet);
}
Now, where am I wrong?
Please plug in the following example. If you don't mind, please just follow my example, and then you will be able to fix your issue.
Controller/Model:
public class AjaxViewModel
{
public string theDate { get; set; }
public string StudentStatue { get; set; }
}
public class HomeController : Controller
{
public string GetAttendance()
{
AjaxViewModel aViewModel = new AjaxViewModel { StudentStatue = "stat4", theDate = "12/24/2005" };
AjaxViewModel aViewModel2 = new AjaxViewModel { StudentStatue = "stat5", theDate = "12/24/2005" };
AjaxViewModel aViewModel3 = new AjaxViewModel { StudentStatue = "stat6", theDate = "12/24/2005" };
IList<AjaxViewModel> data = new List<AjaxViewModel>();
data.Add(aViewModel);
data.Add(aViewModel2);
data.Add(aViewModel3);
JavaScriptSerializer js = new JavaScriptSerializer();
string json = js.Serialize(data);
json = "{ \"data\": " + json;
json = json + " }";
return json;
}
View:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index2020</title>
<script src="~/Scripts/jquery-1.12.4.min.js"></script>
<link href="~/Content/DataTables/css/jquery.dataTables.min.css" rel="stylesheet" />
<script src="~/Scripts/DataTables/jquery.dataTables.min.js"></script>
<script type="text/javascript">
$(function () {
$("#uiDataTable").DataTable({
"ajax": '#Url.Action("GetAttendance")',
columns: [
{
"data": "theDate"
},
{
"data": "StudentStatue"
}
]
});
})
</script>
</head>
<body>
<table id="uiDataTable" class="display table table-striped table-bordered">
<thead>
<tr>
<th>
Date
</th>
<th>
Status
</th>
</tr>
</thead>
</table>
</body>
</html>

Reloading partial views and Ajax - ASP.NET MVC

I have an interesting problem while reloading partial views with ajax. I have a following setup in the master View:
<div>
<div id="items">
#Html.Partial("SubView", Model.Items);
</div>
<div>
SubView is generally a list of items in a table as follows:
<table class="table table-striped">
<tr>
<th>Date</th>
<th>Time</th>
<th></th>
</tr>
#foreach (var item in Model)
{
<tr>
#Html.HiddenFor(modelItem => item.Id)
<td>#Html.DisplayFor(modelItem => item.Date)</td>
<td>#Html.DisplayFor(modelItem => item.Time)</td>
<td>
#Html.ActionLink("Delete", "Delete", new { itemId= item.Id, page = Model.PageNumber }, new { #class = "deleteItem" })
</td>
</tr>
}
DeleteItem Action in the controller does basically the following:
[HttpDelete]
public ActionResult DeleteItem(int itemId, int page)
{
this.dbService.DeletItem(expenseId);
return PartialView("SubView", this.GetPagedList(page));
}
In the script that I refer in the master View I have the following code:
$(document).ready(function () {
// delete expense
$(".deleteItem").click(function () {
$.ajax({
url: this.href,
type: 'delete',
success: function (result) {
$("#items").html(result);
}
});
return false;
});
This works fine the first time, but the second time it only loads the partial View -> since the JavaScript code is not being executed...
I am relatively new to that stuff and I am a bit confused what's going on here.
All 3rd party scripts are rendered in the Layout.cshtml
You can't attach a .click() event to a dynamically generated item. You have to structure it this way:
$(document).on('click', '.deleteItem', function() {
// Deletey stuff here.
});
For partial views to render, you have to make the return type PartialViewResult rather than ActionResult. Because ActionResult causes a redirection.
Try editing your DeleteItem function like this.
[HttpDelete]
public PartialViewResult DeleteItem(int itemId, int page)
{
this.dbService.DeletItem(expenseId);
return PartialView("SubView", this.GetPagedList(page));
}

query.dataTables.min.js - Uncaught TypeError: Cannot read property 'length' of undefined

I am new at JSon and have been searching all over the internet but can't find out where is the error. Can you help me, please? The controller returns the object but nothing is displayed, and it comes out an error saying "Cannot read property 'length' of undefined"`.
This is my main template file:
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<link href="~/Content/bootstrap-theme.min.css" rel="stylesheet" />
<script src="~/scripts/jquery-1.9.1.js"></script>
<script src="~/scripts/bootstrap.min.js"></script>
<!-- Data table -->
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.10/css/dataTables.bootstrap.min.css " />
<script src="https://cdn.datatables.net/1.10.10/js/jquery.dataTables.min.js" type="text/javascript"></script>
<script src="https://cdn.datatables.net/1.10.10/js/dataTables.bootstrap.min.js" type="text/javascript"></script>
This is my table:
<table class="table table-bordered" id="tabela">
<thead>
<tr>
<th>Nome</th>
<th>Quantidade</th>
<th>Preco</th>
<th></th>
</tr>
</thead>
</table>
This is my JSon:
$('#tabela').DataTable({
"columnDefs": [
{ "width": "5%", "targets": [0] }, {
"className": "text-center custom-middle-align",
"targets": [0, 1, 2, 3]
},
],
"language": {
"processing": "<div class='overlay custom-loader-background'><i class='fa fa-cog fa-spin custom-loader-color'></i></div>"
},
"processing": true,
"serverSide": true,
"ajax": {
"url": "/produto/BuscarTodos",
"type": "POST",
"dataType": "JSON"
},
"columns": [{
"data": "Nome"
}, {
"data": "Preco"
}, {
"data": "Quantidade"
}, {
"data": "IdProduto"
}, ]
});
This is my controller:
public JsonResult BuscarTodos()
{
try
{
string dados = "";
// Initialization.
string search = Request.Form.GetValues("search[value]")[0];
string draw = Request.Form.GetValues("draw")[0];
string order = Request.Form.GetValues("order[0][column]")[0];
string orderDir = Request.Form.GetValues("order[0][dir]")[0];
int startRec = Convert.ToInt32(Request.Form.GetValues("start")[0]);
int pageSize = Convert.ToInt32(Request.Form.GetValues("length")[0]);
ProdutoConexao con = new ProdutoConexao();
List<Produto> lista = new List<Produto>();
lista = con.FindAll();
// Total record count.
int totalRecords = lista.Count;
if (!string.IsNullOrEmpty(search) && !string.IsNullOrWhiteSpace(search))
{
// Apply search
lista = lista.Where(p => p.Nome.ToLower().Contains(search.ToLower())).ToList();
}
// Sorting.
lista = this.SortByColumnWithOrder(order, orderDir, lista);
// Filter record count.
int recFilter = lista.Count;
// Apply pagination.
lista = lista.Skip(startRec).Take(pageSize).ToList();
// Loading drop down lists.
var result = this.Json(new
{
draw = Convert.ToInt32(draw),
recordsTotal = totalRecords,
recordsFiltered = recFilter,
data = lista
}, JsonRequestBehavior.AllowGet);
return Json(result);
}
catch (Exception ex)
{
return Json(ex);
}
}
private List<Produto> SortByColumnWithOrder(string order, string orderDir, List<Produto> data)
{
// Initialization.
List<Produto> lista = new List<Produto>();
try
{
// Sorting
switch (order)
{
case "0":
// Setting.
lista = orderDir.Equals("DESC", StringComparison.CurrentCultureIgnoreCase) ? data.OrderByDescending(p => p.Nome).ToList() : data.OrderBy(p => p.Nome).ToList();
break;
}
catch (Exception ex)
{
// info.
Console.Write(ex);
}
// info.
return lista;
}
Just to check that your datatable setup is up and correct I will suggest to create an empty table (no controller) just to make sure that you have everything setup correctly. If that works I'll add your controller and dynamic data.
Datatables REQUIRE a specific HTML table format if it can't find it then you'll get that error.
The simplest table you can check with is the following:
<table>
<thead>
<tr>
<th>header 1</th>
</tr>
</thead>
<tbody>
<tr>
<td>Content 1</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>Footer 1</td>
</tr>
</tfoot>
The footer is optional, everything else is required.
EDIT 1:
Take a look at the similar example they posted

Categories

Resources