Datatable not loading saying awaiting activation json - c#

I am trying to use a datatable and was wondering what i am doing wrong its just stuck on loading and showing waiting to start. This is on my activity controller and the LoadGridData function is called from the scripts below in my index.cshtml.
public ActionResult LoadGridData()
{
// Getting all Customer data
var data = GetAllActivityHeader();
return Json(new { data = data });
}
Here is my GetallActivityHeader function
public async Task<ActionResult<List<ActivityHeader>>> GetAllActivityHeader()
{
return await _activityRepo.GetAllActivityHeader();
}
This is my repositry method which is called above.
public async Task<List<ActivityHeader>> GetAllActivityHeader()
{
using (IDbConnection conn = Connection)
{
if(conn.State == ConnectionState.Closed)
conn.Open();
var result = await conn.QueryAsync<ActivityHeader>("GetActivityHeader");
return result.ToList();
}
}
In My Layout I have the following scripts
#section Scripts{
<script src="//cdn.datatables.net/1.10.9/js/jquery.dataTables.min.js">
</script>
<script>
$(document).ready(function () {
$('#myTable').DataTable({
"ajax": {
"url": "/Activity/LoadGridData",
"type": "GET",
"datatype": "json"
},
"columns": [
{ "data": "Name", "autoWidth": true },
{ "data": "Description", "autoWidth": true },
{ "data": "Phone", "autoWidth": true },
{ "data": "EmployeeName", "autoWidth": true },
{ "data": "SOP", "autoWidth": true },
{ "data": "Status", "autoWidth": true }
]
});
});
</script>
Html
<div class="container">
<br />
<div style="width:90%; margin:0 auto;">
<table id="myTable" class="table table-striped table-bordered dt-responsive nowrap" width="100%" cellspacing="0">
<thead>
<tr>
<th>Name</th>
<th>Description</th>
<th>Phone</th>
<th>EmployeeName</th>
<th>SOP</th>
<th>Status</th>
</tr>
</thead>
</table>
</div>
But when i debug the code i am getting the following issue. Also for some reason my edit and delete buttons are not showing I persume i need to code those before they show. Is there any better components for working with datatables and asp.net core?.
And also here is what my view is showing
Edit 1
Ok so i made the method async and that worked and there data their but its still saying no data in the datatable
public async Task<ActionResult> LoadGridData()
{
// Getting all Customer data
var data = await GetAllActivityHeader();
return Json(new { data = data });
}
Finally this is my class obv I dont want to display all in the datatable so I just used the column headers i wanted or is that not how datatables work?.

Related

No data returned when I incorporate dataTable in ASP.NET MVC

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.

Jquery DataTables serverside in .net core

I am trying to use jQuery DataTables server-side with .net core.
I am using Ajax to call my controller and I have strongly typed View with a table without body.
I am getting data in my controller but it seems I can't display it.
I thought it was JSON (https://dotnetcoretutorials.com/2018/05/05/setting-json-serialization-configuration-at-runtime-on-a-net-core-api/) but I checked and it seems it wasn't.
I tried with this tutorial but still can't find what I am doing wrong.
I just can display the "sDefaultContent" defined in Ajax.
Controller:
[HttpPost]
public async Task<IActionResult> LoadTransaction()
{
var requestFormData = Request.Form;
List<Transactions> data = await ApiClientFactory.Instance.GetInvoice();
dataList = data;
try
{
var listData = ProcessModuleCollection(data, requestFormData);
dynamic response = new
{
Data = listData,
Draw = requestFormData["draw"],
RecordsFiltered = data.Count,
RecordsTotal = data.Count
};
return Ok(response);
//return Json(response);
}
}
View:
<div class="row">
<div>
<div >
</div>
<div class="panel-body">
<table id="example" class="table table-striped table-hover responsive">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.ValueDate)
</th>
<th>
#Html.DisplayNameFor(model => model.StructuredMessage)
</th>
</tr>
</thead>
</table>
</div>
</div>
(function($) {
var generateCustomerTable = $("#example")
.dataTable({
"processing": true,
"serverSide": true,
"ajax": {
"url": "/Home/LoadTransaction",
"method": "POST"
},
"columns": [
{ "data": "ValueDate", "name": "ValueDate", "sDefaultContent": '0-0-0000', "autoWidth": true },
{ "data": "StructuredMessage", "name": "StructuredMessage", "sDefaultContent": '0-0-0000', "autoWidth": true },
],
"ordering": true,
"paging": true,
"pagingType": "full_numbers",
"pageLength": 10
});
})(jQuery);
here is the printScreen of my console
console PrintScreen
i must admit as often the community StackOverFlow had already the answer
the thing missing is in the ajax call datasrc
this post helps me understanding what i was trying to do
and reading a bit more comments
'dataFilter': function(data){
var json = jQuery.parseJSON( data );
json.RecordsTotal = json.total;
json.RecordsFiltered = json.total;
json.Data = json.list;
return JSON.stringify( json ); // return JSON string
}
in this particular case regarding what i am sending from my controller

problem loading Jquery Datatable using a textbox

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) }
});

MVC jquery datatable search from external input

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!

Error in binding json data from Ajax source in jquery data tables

I am getting error in binding JSON data to constuct a data table.
My JSON is of the following:
[
{
"ID": 1,
"Number": "2",
"Name": "Avinash"
},
{
"ID":2,
"Number":"21",
"Name":"XYZ"
},
{
"ID": 3,
"Number": "20",
"Name": "KRR"
}
]
I am binding this to jquery datatable as below:
$(document).ready(function () {
$('#table_id').dataTable({
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": '<%:Url.Action("LoadData","Home")%>'
});
$('#table_id').css("width", "100%")
});
My Table Structure is as follows:
<table id="table_id" border="0" class="display" cellpadding="1" cellspacing="1" align="center">
<thead>
<tr>
<th>ID</th>
<th>Number</th>
<th>Name</th>
</tr>
</thead>
</table>
I am getting error as follows:
Datatables Warning(tableid="table_id"):Requested Unknown Parameter'0' from the datasource for row 0
My Controller is as follows:
public ActionResult LoadData()
{
var Data = new DataTable();
Data=DataModel.LoadData();
var JsonData = JsonConvert.SerializeObject(Data, Formatting.None);
return Json(new
{
aaData = JsonData
}, JsonRequestBehavior.AllowGet);
}
Please help..

Categories

Resources