I'm trying to load data in datatables (1.10.9) via ajax to an ASP MVC controller.
I have the following table:
<table id="Demo" class="table table-striped" cellspacing="0">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.Code)
</th>
<th>
#Html.DisplayNameFor(model => model.Description)
</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
And the following script
<script>
$(document).ready(function () {
$('#Demo').DataTable({
ajax: 'GetVehicle',
dataSrc: '',
columns: [
{ data: 'Code' },
{ data: 'Description' }
]
});
});
</script>
In ASP MVC i have the following Controller:
[HttpGet]
public JsonResult GetVehicle()
{
return Json(db.vehicletype.ToList(), JsonRequestBehavior.AllowGet);
}
And when this controller is called by the ajax request in the chrome inspector i see the following answer:
[
{"vehicle":[],"Id":1,"Code":"Car1","Description":"Car1 Description"},
{"vehicle":[],"Id":2,"Code":"Car2","Description":"Car2 Description"}
]
Why in the datatables i don't see any rows? I only see "Loading...."
In the chrome inspector, in the console, i see only this error:
Uncaught TypeError: Cannot read property 'length' of undefined
in the jquery.dataTables.min.js
UPDATE
Resolved changing the asp mvc controller into:
public JsonResult GetVehicle()
{
return Json(new { data = db.vehicletype.ToList() }, JsonRequestBehavior.AllowGet);
}
Related
I'm still a newbie and currently learning how to use Laravel 7.
My problem is, I tried to pass my data from the controller by using an AJAX request on
my child page. I noticed that when I tried to pass the data from my child page, the page won't
receive it but somehow it's working on a master page (where I didn't use any Blade directives).
I tried to dd() the data in the controller and it does show that there is data.
But it won't pass it to the child page. All the JS files and custom script that I push does
come out on the child page.
blade
code
index.blade.php (child page)
#extends('layouts.app')
#section('content')
<div class="container">
<div class="container mt-5">
<h2 class="mb-4">Laravel 7 Yajra Datatables Example</h2>
<table class="table table-bordered yajra-datatable">
<thead>
<tr>
<th class="text-center">#</th>
<th class="text-center">Name</th>
<th class="text-center">Batch</th>
<th class="text-center">Graduation Year</th>
<th class="text-center">Mobile</th>
<th class="text-center">Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
#endsection
#push('child-scripts')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/dataTables.bootstrap4.min.js"></script>
<script type="text/javascript">
$(function () {
var table = $('.yajra-datatable').DataTable({
processing: true,
serverSide: true,
ajax: "{{ route('alumni-list') }}",
columns: [
{data: 'DT_RowIndex', name: 'DT_RowIndex'},
{data: 'name', name: 'name'},
{data: 'batch_year', name: 'batch_year'},
{data: 'graduation_year', name: 'graduation_year'},
{data: 'contact_no', name: 'contact_no'},
{
data: 'action',
name: 'action',
orderable: true,
searchable: true
},
]
});
});
</script>
#endpush
AlumniController.php
class AlumniController extends Controller
{
public function index(Request $request)
{
// dd(Profile::latest()->get());
if ($request->ajax()) {
$data = Profile::latest()->get();
return Datatables::of($data)
->addIndexColumn()
->addColumn('action', function($row){
$btn = 'Edit Delete';
return $btn;
})
->rawColumns(['action'])
->make(true);
}
return view('admin.users.index');
}
}
Alumni Route
Route::get('alumni', [
'uses' => 'AlumniController#index',
'as' => 'alumni-list'
]);
Thank you for your time, sir.
Solved it after MORE googling done.
Make sure to add defer inside your DataTable CDN.
Example:
<script src = "http://cdn.datatables.net/1.10.18/js/jquery.dataTables.min.js" defer ></script>
Here's the link where I found the answer:
https://datatables.net/forums/discussion/50869/typeerror-datatable-is-not-a-function-datatable-laravel
For more understanding on why defer is added:
https://www.growingwiththeweb.com/2014/02/async-vs-defer-attributes.html
use Yajra\DataTables\Contracts\DataTable;
use Yajra\DataTables\Facades\DataTables;
please use this two line in your controller
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);
I am currently working in Asp.net MVC in Visual Studio 2017. I am new to working with Asp.net MVC and can not get the values i am needing.
I have a table of questions that are all displayed in a table on my view page. Each one of the questions have a Boolean value that shows as check boxes when they are being displayed. I am currently trying to write a script to get the checkbox value of true or false and where that checkbox is checked I am trying to get the Id of the question in the current row.
This is my view where I am displaying the questions.
#model IEnumerable<CapstoneApplication.Models.Question>
#{
ViewBag.Title = "Index";
}
<h2>Questions: Admin View</h2>
<script src="~/Scripts/jquery-3.3.1.min.js"></script>
<script src="~/Scripts/SaveCheckBox.js"></script>
<p>
#Html.ActionLink("Create Question", "Create")
</p>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.IsPartOfGame)
</th>
<th>
#Html.DisplayNameFor(model => model.Category.CategoryName)
</th>
<th>
#Html.DisplayNameFor(model => model.QuestionDescription)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.CheckBoxFor(modelItem=>item.IsPartOfGame, new {onclick = "SaveCheckBox(this)" })
</td>
<td>
#Html.DisplayFor(modelItem => item.Category.CategoryName)
</td>
<td>
#Html.DisplayFor(modelItem => item.QuestionDescription)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new {id = item.Id}) |
#Html.ActionLink("Delete", "Delete", new {id = item.Id})
</td>
</tr>
}
</table>
This is the script I am currently using.
function SaveCheckBox(checkboxInput) {
$.ajax({
type: 'GET',
url: 'Index',
data: {idValue: checkboxInput.closest("tr").getAttribute("id"),
newValue: checkboxInput.checked },
dataType: 'json'
});
}
Finally this is the method the script calls to give the values to.
public ActionResult Index(bool? newValue, int? idValue)
{
//save to database here
var questions = db.Questions.Include(q => q.Category);
return View(questions.ToList());
}
The problem I am having is that newValue always returns the correct value of being either true or false but idValue is always null it never grabs the id of the question in the row of the checkbox that was checked.
I would place the id as the data attribute in your CheckboxFor
#Html.CheckBoxFor(
modelItem=>item.IsPartOfGame
, new {onclick = "SaveCheckBox(this)", data_itemid = item.Id}
})
Then I would use this for your javascript
function SaveCheckBox(checkboxInput) {
$.ajax({
type: 'GET',
url: 'Index',
data: {
idValue: checkboxInput.dataset.itemid
, newValue: checkboxInput.checked
},
dataType: 'json'
});
}
I am using jquery datatable in my application, plugin link https://datatables.net/
I want to populate my datatable with JSON, but I am failed.here is my code.
HTML:
<table id="example" class="display" width="100%" cellspacing="0">
<thead>
<tr>
<th>id</th>
<th>Name</th>
<th>Code</th>
<th>Description</th>
<th>isActive</th>
</tr>
</thead>
<tfoot>
<tr>
<th>id</th>
<th>Name</th>
<th>Code</th>
<th>Description</th>
<th>isActive</th>
</tr>
</tfoot>
<tbody>
</tbody>
</table>
JS:
$(document).ready(function() {
console.log("hi ready");
$('#example').DataTable({
retrieve: true,
ajax: {
url: '/ProductLicensingApplication/feature/list',
dataSrc: ''
},
"columns": [
{ "data": "id" },
{ "data": "name" },
{ "data": "code" },
{ "data": "description" },
{ "data": "isActive" }
]
});
} );
my json
but I am not able to populate data into the table as the table shows no data available in the table..you can see in the image
please tell me what is the problem in my code...
As written in documentation. The ajax.dataSrc option is used to tell DataTables where the data array is in the JSON structure. An empty string is a special case which tells DataTables to expect an array.
In your case JSON is an object and you should set dataSrc : 'features'
Ahmad,
Either set dataSrc : 'features' or if possible rename the attribute name 'features' to 'data' in the response data.
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));
}