Reload Datatable with parameter to ajax call - asp.net-mvc

Good day all, I have a project that lists rows of a specific 'node'. Each node has the ability to have a parent of that node. Think simple Hierarchy pattern.
Well. What I want to happen is, on single click of the row, i want it to be highlighted, but on double click of a row, i want the table to refresh but with the new data. The data will be based off of who has a parent of this id.
<div class="table table-striped table-bordered">
View Parent
<input id="parentID" name="ParentID" value="" type="hidden">
<table id="myDatatable">
<thead>
<tr>
<th>NodeID</th>
<th>Name</th>
<th>Desc</th>
<th>Active</th>
</tr>
</thead>
</table>
</div>
<script src="~/lib/DataTables-1.10.16/js/jquery.dataTables.js"></script>
<script src="~/lib/DataTables-1.10.16/js/dataTables.bootstrap4.min.js"></script>
<script>
$(document).ready(function () {
var oTable = $('#myDatatable').DataTable({
"ajax": {
"url": '/Node/GetNodes?pParentID=' + $('#parentID').val(),
"type": "get",
"datatype": "json"
},
"autoWidth": true,
"columns": [
{
"data": "NodeID",
"render": function (pID) {
return '<input id="NodeID" value="'+pID+'" disabled/>';
}
},
{ "data": "Name", "width": "100%" },
{ "data": "Desc", "width": "100%" },
{
"data": "IsActive", "width": "50px",
'searchable': false,
"render": function (pActive) {
var status = pActive ? 'checked="checked"' : "";
return '<input class="CheckBox" disabled type="checkbox" ' + status + '" />';
}
}
]
});
$('#myDatatable tbody').on('click', 'tr', function () {
if ($(this).hasClass('selected')) {
$(this).removeClass('selected');
}
else {
oTable.$('tr.selected').removeClass('selected');
$(this).addClass('selected');
$('#parentID').val($('td #NodeID', this).val());
}
});
$('#myDatatable tbody').on('dblclick', 'tr', function() {
if ($(this).hasClass('selected')) {
$(this).removeClass('selected');
}
else {
oTable.$('tr.selected').removeClass('selected');
$('#parentID').val($('td #NodeID', this).val());
oTable.ajax.reload(); // DOESN"T DO WHAT I EXPECT
}
});
$("#parentIDLink").click(function () {
oTable.ajax.reload();
});
});
</script>
Above is the html for that page. Below is the MVC code that gets called to draw the list. Essentially grab all node if the id is null but grab nodes that have a specific parent if the value is not null
public ActionResult GetNodes(string pParentID)
{
if (pParentID == null || pParentID == "null" || pParentID == string.Empty)
return base.Json(new { data = m_Context.Nodes.ToList() },
new JsonSerializerSettings());
else
return base.Json(new { data = m_Context.Nodes.Where(m => m.NodeID == pParentID).ToList() },
new JsonSerializerSettings());;
}
Am i going about this the wrong way?

Create a function that relodes your data according to your selection. Inside double click event handler, call that function
function LoadDataTable() {
$.ajax({
type: "POST",
url: "/Node/GetNodes",
data: { pParentID: $('#parentID').val() },
success: function(result){
oTable.clear().draw();
oTable.rows.add(result).draw();
}
});
}
$('#myDatatable tbody').on('dblclick', 'tr', function() {
if ($(this).hasClass('selected')) {
$(this).removeClass('selected');
}
else {
oTable.$('tr.selected').removeClass('selected');
$('#parentID').val($('td #NodeID', this).val());
LoadDataTable();
}
});

Related

checkBox filter table when field is null

I have a table with orders, one of the columns is "Tracking number"
Added a checkbox to so user can choose when to see all orders or just orders without tracking numbers.
here is the checkbox in view :
<div id="TrackingNumber">
<input type="checkbox" name="pos" value=true/>Show All
</div>
the javascript called is :
<script>
$(document).ready(function () {
$.fn.dataTable.ext.search.push(
function (settings, searchData, index, rowData, counter) {
var positions = $('input:checkbox[name="pos"]:checked').map(function () {
return this.value;
}).get();
if (positions.length === 0) {
return true;
}
if (positions.indexOf(searchData[1]) !== -1) {
return true;
}
return false;
}
)
var table = $('#tblData').DataTable();
$('input:checkbox').on('change', function () {
table.draw();
});
});</script>
when checkbox is checked it shows 0 records and when unchecked it shows all.
i want it to show all records when checkbox is checked and show only records WITHOUT tracking numbers
when Unchecked,
Help will be much appreciated :)
Here is a demo:
View:
<table id="tblList" class="table table-striped table-bordered" style="width:100%">
<div>
<input type="checkbox" id="pos" checked="checked"/>Show All
</div>
<thead class="thead-dark">
<tr class="table-info">
<th>pal</th>
<th>via</th>
<th>con</th>
<th>TrackingNumber</th>
</tr>
</thead>
</table>
#section scripts{
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.js"></script>
<script type="text/javascript">
$(function () {
var url = "GetAllPakingList";
LoadPack(url);
})
function LoadPack(url) {
$('#tblList').DataTable({
destroy: true,
ajax: {
url: url,
},
columns: [
{ "data": "pal", responsivePriority: 1, "searchable": true },
{ "data": "via", responsivePriority: 2, "searchable": true },
{ "data": "con", responsivePriority: 3, "searchable": true },
{ "data": "trackingNumber", responsivePriority: 4, "searchable": true },
],
});
};
$.fn.dataTable.ext.search.push(
function (settings, data, dataIndex) {
var trackingNumber = data[3];
if ($('#pos').prop("checked") != true && trackingNumber!="") {
return false;
} else {
return true;
}
}
);
$('input:checkbox').on('change', function () {
var table = $('#tblList').DataTable();
table.draw();
});
</script>
}
ListOutput:
public class ListOutput
{
public string pal { get; set; }
public string via { get; set; }
public string con { get; set; }
public string TrackingNumber { get; set; }
}
result:

Hide/Show Editable links in webGrid CSHTML code

I am trying to Hide/Show the 'Edit' link in each row of a given Grid. Basically only few user roles have the access to Modify the information. I wrote a method ActionResult in controller class to check the user access and returning Boolean value. Based on True/False I need to Hide/Show the 'Edit' Links in a grid. The design code is written in MVC CSHTML. Please suggest how it can be achieved. I tried using JQuery but I can hide the Edit column only for the first row of the grid. Below is the code in CSHTML and Jquery.
CSHTML Code
<table border="1" cellpadding="0" cellspacing="1" style="width: 90%;"><tr>
<td>
#grid.GetHtml(tableStyle: "webGridMedium",
headerStyle: "header",
alternatingRowStyle: "alt",
selectedRowStyle: "select",
columns: grid.Columns(
grid.Column("BeginDate", "Begin Date", style: "description"),
grid.Column("Status", "Status", style: "description"),
grid.Column("", style: "description10", format: #<a class="edit-status" id="btnEditStatus" href="">Edit</a>)
))
</td>
</tr>
</table>
JQuery Code: The parameter data is boolean value I get it from Controller class.
<script>
$(document).ready(function () {
checkAccess();
}
function checkAccess() {
// debugger;
$.ajax({
url: '/Employee/CheckAccess',
type: 'POST',
data: {},
success: function (data) {
if (data == false) {
document.getElementById("btnEditStatus").style.visibility = "hidden";
}
else if (data = true) {
document.getElementById("btnEditStatus").style.visibility = "";
}
},
error: (function (result) {
alert("Failed access! Please contact administrator.");
})
})
}
</script>
<script>
function checkAccess() {
// debugger;
$.ajax({
url: '/Application/CheckAccess',
type: 'POST',
data: {},
success: function (data) {
if (data == false) {
$('.modaltable tr').each(function (i, row) {
$(this).find('.edit-status').hide();
});
}
else if (data = true) {
// your code
}
},
error: (function (result) {
alert("Please contact IT administrator for access.");
})
})
}
</script>

How to get the selected Table cell value in datatable

I am using jquery-2.0.3.min.js, bootstrap.min.js, jquery-ui-1.10.3.min.js, DataTables-1.9.4 with tabletools, datatables.net/blog/Twitter_Bootstrap_2
My View
<div id="windowDepartment" title="Departments"></div>
<table cellpadding="0" cellspacing="0" border="0" class="table table-striped table-bordered table-hover table-condensed" id="DepartmentTable">
<thead>
<tr>
<th>departmentID</th>
<th>departmentName</th>
<th>description</th>
<th>Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Datatable initialisation Script
$(document).ready(function () {
oDepartmentTable = $('#DepartmentTable').dataTable(
{
"sDom": "T<'clear'>lfrtip",
"bJQueryUI": true,
"sPaginationType": "full_numbers",
"bServerSide": true,
"sAjaxSource": "Department/AjaxList",
"aaSorting": [[2, 'asc'], [3, 'asc']],
"aoColumns": [
{ "mDataProp": "departmentID", "sType": "string", "bVisible": false, "bSearchable": false },
{ "mDataProp": "departmentName", "sType": "string", "bVisible": true, "bSearchable": true },
{ "mDataProp": "description", "sType": "string", "bVisible": true, "bSearchable": true },
{ "mDataProp": null,"bSearchable": false,
"sDefaultContent": '<div class="btn-group"><a class="btn btn-mini dropdown-toggle" data-toggle="dropdown" href="#"><span class="icon-circle-arrow-down"></span></a><ul class="dropdown-menu"><li><a class="editDepartment"> <i class="icon-pencil"></i> Edit</a></li><li><a class="deleteDepartment"> <i class="icon-trash"></i> Delete</a></li></ul></div>'
}
],
"oTableTools": {
"sSwfPath": "/Content/DataTables-1.9.4/extras/TableTools/media/swf/copy_csv_xls_pdf.swf"
}
});
});
EDIT FORM SCRIPT
$(document).ready(function () {
$('#DepartmentTable tbody').on('click', 'a.editDepartment', function (e) {
e.preventDefault();
//1. Dose not work shows "not available"
var aData = oDepartmentTable.fnGetData(this)
//2. Gets the correct ID if "bVisilble=true"
var departmentid = $(this).parent().parent().parent().parent().parent().children()[0].innerHTML ;
//goto Edit Controller. DepartmentID is required here
$.get('Department/Edit/' + departmentid , function (data) {
$('div#windowDepartment').html(data);
//Open Dialog box
$("#windowDepartment").dialog().dialog({
resizable: true,
height: 500,
width: 500,
modal: true,
buttons:
{
Edit: function () {
editDepartment(); //Saves the data. Works fine
}, // end ok button
Cancel: function () {
$(this).dialog("close");
}
}, //end buttons
close: function () {
$(this).dialog("close");
}
}); //end modal edit
});
});
});
My Problem. (in EDIT FORM SCRIPT)
I need the DepartmentID to pass to my controller ('Department/Edit/' + departmentid)
My observations
1) var aData = oDepartmentTable.fnGetData(this) always shows "not available" in chrome console.
2) var departmentid = $(this).parent().parent().parent().parent().parent().children()[0].innerHTML gets the correct departmentID if i use "bVisible": true in datatable initialisation.
(3) I dont want to show departmentID to the end user. if i make "bVisible": false in datatable initialisation then
var departmentid = $(this).parent().parent().parent().parent().parent().children()[0].innerHTML returns the departmentName
Thanks
Look at the discussion in the datatables forum here and fnGetPosition
Try this clickhandler instead :
$(document).ready(function () {
$('#DepartmentTable tbody tr').on('click', function (e) {
// get the position of the current data from the node
var aPos = oDepartmentTable.fnGetPosition( this );
// get the data array
var aData = oDepartmentTable.fnGetData( aPos[0] );
// get departmentID for the row
var departmentID = aData[aPos].departmentID;
console.log(departmentID);
// ... do your stuff here, eg
//goto Edit Controller. DepartmentID is required here
//$.get('Department/Edit/' + departmentid , function (data) {
//..
//..
});
});
It works for me. However, not quite as the docs says. Also, I first tried out with datatables 1.9.1 - it didnt work at all. Guess this area of datatables have had some bugs and have been refactored over the versions.

Knockoutjs Custom bindig with jQueryUI Dialog

I'm trying to make a custom binding based on this code, http://jsfiddle.net/rniemeyer/WpnTU/ , Mine after a field checkbox is selected then open a jQueryUI dialog. Here is the code: http://jsfiddle.net/superjohn_2006/UFEg6/ , another question is it posible to acomplish this without a template.
<table>
<tbody data-bind="foreach: records">
<tr data-bind="foreach: fields">
<th align="left">
<input type="checkbox" data-bind="checked: chkedValue" /><span data-bind=" text: field"></span>
</th>
</tr>
<tr data-bind="foreach: fields">
<th align="left"><a data-bind="click: $root.addFormatting" href="#">Add Formatting</a></th>
</tr>
<tr data-bind="foreach: row">
<td data-bind="text: value"></td>
</tr>
</tbody>
</table>
<div id="details" data-bind="jqDialog: { autoOpen: false, resizable: false, modal: true }, template: { name: 'editTmpl', data: selectedField }, openDialog: selectedField">
</div>
<script id="editTmpl" type="text/html">
<p>
<label>Selected Field: </label>
<span data-bind="value: field" />
</p>
<button data-bind="jqButton: {}, click: $root.accept">Accept</button>
<button data-bind="jqButton: {}, click: $root.cancel">Cancel</button>
</script>
**The model
// custom binding
ko.bindingHandlers.jqDialog = {
init: function(element, valueAccessor) {
var options = ko.utils.unwrapObservable(valueAccessor()) || {}; // initialize a jQuery UI dialog
$(element).dialog(options);
// handle disposal
ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
$(element).dialog("destroy");
});
}
};
//custom binding handler that opens/closes the dialog
ko.bindingHandlers.openDialog = {
update: function(element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor());
if (value) {
$(element).dialog("open");
} else {
$(element).dialog("close");
}
}
};
//custom binding to initialize a jQuery UI button
ko.bindingHandlers.jqButton = {
init: function(element, valueAccessor) {
var options = ko.utils.unwrapObservable(valueAccessor()) || {};
//handle disposal
ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
$(element).button("destroy");
});
$(element).button(options);
}
};
var resultsData = [
{ fields: [{ field: "Field1", chkedValue: false }, { field: "Field2", chkedValue: false }] },
{ row: [{ value: "1" }, { value: "True" }] },
{ row: [{ value: "2" }, { value: "False" }] }
];
var TableModel = function (records) {
var self = this;
self.records = ko.observableArray(ko.utils.arrayMap(records, function (record) {
return { fields: ko.observableArray(record.fields), row: ko.observableArray(record.row) };
}));
self.selectedField = ko.observable();
self.addFormatting = function (formatToAdd) {
self.selectedField();
};
};
this.accept = function() {
},
this.cancel = function() {
}
ko.applyBindings(new TableModel(resultsData));
the following couple of lines need to be changed.
span data-bind="value: field"
for:
span data-bind="text: $data.field"
and,
self.selectedField();
for:
self.selectedField(formatToAdd);
modified code is in the same jsFiddle, jus add: /1/
to the end of the url address.

Add Text Search to Kendo Grid

I am trying out the open source Kendo Grid for the first time. I have the basic grid up and running just fine, but now I need to add a search feature, with a search on first and last names. I am trying to do it in ajax but I am stuck on an error:
Error: Cannot call method 'read' of undefined
my code:
<div id="search-index">
<div class="editor-field">
<label>First Name:</label>
#Html.TextBox("FirstName")
<label style = "margin-left: 15px;">Last Name:</label>
#Html.TextBox("LastName", "", new { style = "margin-right: 15px;" })
</div>
<div id="search-controls-index">
<input type="button" id="searchbtn" class="skbutton" value="Search" />
<input type="button" id="addPersonbtn" class="skbutton" value="Add New Person" onclick="location.href='#Url.Action("AddPerson", "Person")'"/>
</div>
</div>
<div id="index-grid"></div>
</div>
$(document).ready(function () {
var grid = $('#index-grid').kendoGrid({
height: 370,
sortable: true,
scrollable: true,
pageable: true,
dataSource: {
pageSize: 8,
transport: {
read: "/Home/GetPeople",
dataType:"json"
}
},
columns: [
{ field: "FirstName", title: "First Name" },
{ field: "LastName", title: "Last Name" },
{ field: "Gender", title: "Gender" },
{ field: "DOB", title: "Date of Birth", template: '#= kendo.toString(new Date(parseInt(DOB.substring(6))), "MM/dd/yyyy") #' },
{ field: "IsStudent", title: "Is a Student?" }]
});
$("#searchbtn").on('click', function () {
var fsname = $("#FirstName").val();
var ltname = $("#LastName").val();
$.ajax({
type: 'GET',
url: '#Url.Content("~/Home/GetPeople")',
data: { fname: fsname, lname: ltname },
success: function (data) {
grid.dataSource.read();
},
error: function () {
$("#index-grid").html("An error occured while trying to retieve your data.");
}
});
});
});
Should matter, but here is my controller (using asp MVC 3):
public JsonResult GetPeople(string fname, string lname)
{
if (((fname == "") && (lname == "")) || ((fname == null) && (lname == null)))
{
var peopleList = repo.GetPeople();
return Json(peopleList, JsonRequestBehavior.AllowGet);
}
else
{
var personResult = repo.GetSearchResult(fname, lname);
return Json(personResult, JsonRequestBehavior.AllowGet);
}
}
The problem is that $("#grid").kendoGrid() returns a jQuery object which doesn't have a dataSource field. Here is how to get a reference to the client-side object: http://docs.kendoui.com/getting-started/web/grid/overview#accessing-an-existing-grid

Resources