MVC jquery datatable search from external input - c#

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!

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.

Datatable not loading saying awaiting activation json

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?.

Editable jquery datatable with sql database

<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?

Initialize and Populate a dataTable in asp.net

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>

How do I use jquery templates with JSON data?

I am trying to write some jquery code to retrieve a list of servers from a cloud account and display them in a table. When I load my page, my javascript executes and the proper JSON is returned, but when I try to use a jquery template to generate my html, I never get any output. Can anyone help me figure out where my problem is?
Javascript to fetch server data
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
url: '../../api/server/getservers',
type: 'POST',
success: function (result) {
$('#serverTemplate').tmpl(result).appendTo('#serverTable');
},
});
});
</script>
Jquery Template Javascript
<script id="serverTemplate" type="text/x-jQuery-tmpl">
{{each servers}}
<tr>
<td>${status}</td>
<td>${name}</td>
</tr>
{{/each}}
</script>
HTML
<table>
<thead>
<tr>
<th>Status</th>
<th>Server Name</th>
</tr>
</thead>
<tbody id="serverTable">
</tbody>
</table>
JSON Example
{
"servers": [
{
"progress": 100,
"id": 11111111,
"imageId": 1,
"flavorId": 1,
"status": "ACTIVE",
"name": "SERVER-1",
"hostId": "abcdefghijklmnopqrstuvwxyz",
"addresses": {
"public": [
"1.1.1.1"
],
"private": [
"2.2.2.2"
]
},
"metadata": {}
},
{
"progress": 100,
"id": 22222222,
"imageId": 2,
"flavorId": 2,
"status": "ACTIVE",
"name": "Server-2",
"hostId": "zxywufvslakdkdkdkdkdkdkdkdk",
"addresses": {
"public": [
"3.3.3.3"
],
"private": [
"4.4.4.4"
]
},
"metadata": {}
}
]
}
jQuery version 1.5.1
jQuery-tmpl
version beta 1
I solved the issue by changing the success function and adding an explicit parse of the JSON to an array.
var servers = jQuery.parseJSON(result);
$('#serverTemplate').tmpl(servers).appendTo('#serverTable');

Categories

Resources