Datatable Refresh With Pusher AngularJS - javascript

I really tried hard to refresh datatable with new data but couldn't achieve it. I initialize datatable with ng-repeat and get the data from api. Any idea would be perfect. Here is my html code:
<table class="table table-bordered table-striped table-hover js-dataTable-full dt-responsive" width="100%" id="dataTableId">
<thead>
<tr>
<th>NO</th>
<th>COMPANY CODE</th>
<th>CREATED DATE</th>
<th>DESCRIPTION</th>
<th>DUE DATE</th>
<th>CREATED BY</th>
<th>STATUS</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="document in documents" ng-if="document.status == 0 || document.status == 2">
<td>{{document.group_order_id}}</td>
<td>{{document.company.code}}</td>
<td>{{document.created}}</td>
<td>{{document.description}}</td>
<td>{{document.due_date}}</td>
<td>{{document.created_by_user.first_name}} {{document.created_by_user.last_name}}</td>
<td><span>Status</span></td>
</tr>
</tbody>
</table>
And here is my controller:
// Init full DataTable, for more examples you can check out https://www.datatables.net/
var initDataTableFull = function () {
if (!$.fn.dataTable.isDataTable('.js-dataTable-full')) {
jQuery('.js-dataTable-full').dataTable({
"language": {
"sProcessing": "İşleniyor...",
"sLengthMenu": "Sayfada _MENU_ Kayıt Göster",
"sZeroRecords": "Eşleşen Kayıt Bulunmadı",
"sInfo": " _TOTAL_ Kayıttan _START_ - _END_ Arası Kayıtlar",
"sInfoEmpty": "Kayıt Yok",
"sInfoFiltered": "( _MAX_ Kayıt İçerisinden Bulunan)",
"sInfoPostFix": "",
"sSearch": "Bul:",
"sUrl": "",
"oPaginate": {
"sFirst": "İlk",
"sPrevious": "Önceki",
"sNext": "Sonraki",
"sLast": "Son"
}
},
"order" : [[0, "desc"]]
});
}
};
// DataTables Bootstrap integration
var bsDataTables = function () {
var DataTable = jQuery.fn.dataTable;
// Set the defaults for DataTables init
jQuery.extend(true, DataTable.defaults, {
dom: "<'row'<'col-sm-6'l><'col-sm-6'f>>" +
"<'row'<'col-sm-12'tr>>" +
"<'row'<'col-sm-6'i><'col-sm-6'p>>",
renderer: 'bootstrap',
oLanguage: {
sLengthMenu: "_MENU_",
sInfo: "Showing <strong>_START_</strong>-<strong>_END_</strong> of <strong>_TOTAL_</strong>",
oPaginate: {
sPrevious: '<i class="fa fa-angle-left"></i>',
sNext: '<i class="fa fa-angle-right"></i>'
}
}
});
// Default class modification
jQuery.extend(DataTable.ext.classes, {
sWrapper: "dataTables_wrapper form-inline dt-bootstrap",
sFilterInput: "form-control",
sLengthSelect: "form-control"
});
// Bootstrap paging button renderer
DataTable.ext.renderer.pageButton.bootstrap = function (settings, host, idx, buttons, page, pages) {
var api = new DataTable.Api(settings);
var classes = settings.oClasses;
var lang = settings.oLanguage.oPaginate;
var btnDisplay, btnClass;
var attach = function (container, buttons) {
var i, ien, node, button;
var clickHandler = function (e) {
e.preventDefault();
if (!jQuery(e.currentTarget).hasClass('disabled')) {
api.page(e.data.action).draw(false);
}
};
for (i = 0, ien = buttons.length; i < ien; i++) {
button = buttons[i];
if (jQuery.isArray(button)) {
attach(container, button);
}
else {
btnDisplay = '';
btnClass = '';
switch (button) {
case 'ellipsis':
btnDisplay = '…';
btnClass = 'disabled';
break;
case 'first':
btnDisplay = lang.sFirst;
btnClass = button + (page > 0 ? '' : ' disabled');
break;
case 'previous':
btnDisplay = lang.sPrevious;
btnClass = button + (page > 0 ? '' : ' disabled');
break;
case 'next':
btnDisplay = lang.sNext;
btnClass = button + (page < pages - 1 ? '' : ' disabled');
break;
case 'last':
btnDisplay = lang.sLast;
btnClass = button + (page < pages - 1 ? '' : ' disabled');
break;
default:
btnDisplay = button + 1;
btnClass = page === button ?
'active' : '';
break;
}
if (btnDisplay) {
node = jQuery('<li>', {
'class': classes.sPageButton + ' ' + btnClass,
'aria-controls': settings.sTableId,
'tabindex': settings.iTabIndex,
'id': idx === 0 && typeof button === 'string' ?
settings.sTableId + '_' + button :
null
})
.append(jQuery('<a>', {
'href': '#'
})
.html(btnDisplay)
)
.appendTo(container);
settings.oApi._fnBindAction(
node, {action: button}, clickHandler
);
}
}
}
};
attach(
jQuery(host).empty().html('<ul class="pagination"/>').children('ul'),
buttons
);
};
// TableTools Bootstrap compatibility - Required TableTools 2.1+
if (DataTable.TableTools) {
// Set the classes that TableTools uses to something suitable for Bootstrap
jQuery.extend(true, DataTable.TableTools.classes, {
"container": "DTTT btn-group",
"buttons": {
"normal": "btn btn-default",
"disabled": "disabled"
},
"collection": {
"container": "DTTT_dropdown dropdown-menu",
"buttons": {
"normal": "",
"disabled": "disabled"
}
},
"print": {
"info": "DTTT_print_info"
},
"select": {
"row": "active"
}
});
// Have the collection use a bootstrap compatible drop down
jQuery.extend(true, DataTable.TableTools.DEFAULTS.oTags, {
"collection": {
"container": "ul",
"button": "li",
"liner": "a"
}
});
}
};
var table = $('.js-dataTable-full');
$http({
url: 'https://standards-and-partners-api.azurewebsites.net/documents',
method: 'GET',
headers: {
'Accept': 'application/json'
}
}).then(function (response) {
$scope.documents = response.data.data;
$timeout(function () {
// Init Datatables
bsDataTables();
initDataTableFull();
});
});
// Enable pusher logging - don't include this in production
Pusher.logToConsole = true;
var pusher = new Pusher('--------------', {
cluster: 'eu',
encrypted: true
});
var channel = pusher.subscribe('my-channel');
channel.bind('my-event', function(data) {
table.empty();
table.dataTable()._fnInitialise();
$http({
url: 'https://standards-and-partners-api.azurewebsites.net/documents',
method: 'GET',
headers: {
'Accept': 'application/json'
}
}).then(function (response) {
$scope.documents = response.data.data;
$scope.$apply();
});
});
What should I do to reload my datatable with new data ? Thanks guys.

Related

$refs resetFields not a function AntDesign

I have a problem with reseting fields of my form.
I have a form. The user can adding another forms and another ...
If everything is OK, I would like to recording data in my DB and in my store AND reset all of inputs of my form. This is this last point I cannot do.
I have tried different solutions but It does not work.
This is my code :
<div v-for="(question, index) in questionsSignaletiques" :key="index" class="blockQuestion" >
<!--form to add questions : one form per question, each form have a different name in the ref -->
<a-form-model
layout="inline"
:ref="'p' + index"
>
<p>New question</p>
<a-alert v-if="question.error.here" type="error" :message="question.error.message" show-icon />
<a-form-model-item>
<a-input v-model="question.question.type" placeholder="Title">
</a-input>
</a-form-model-item>
<a-form-model-item>
<a-input v-model="question.question.item" placeholder="Item">
</a-input>
</a-form-model-item>
<br><br>
<a-form-model-item label="Question multiple" prop="delivery">
<a-switch v-model="question.question.multiple" />
</a-form-model-item>
<a-form-model-item label="Obligatoire" prop="delivery">
<a-switch v-model="question.question.obligatoire" />
</a-form-model-item>
<br><br>
<div class="blockChoices">
<div v-for="subrow in question.question.choices">
<a-form-model-item>
<a-input v-model="subrow.name" placeholder="Choix">
</a-input>
</a-form-model-item>
</div>
</div>
<a-button #click="addChoice(question)" type="secondary">Add a choice</a-button>
</a-form-model>
</div>
<div>
<a-button #click="addItem" type="secondary">Add a question</a-button>
</div>
<br>
<div>
<a-button #click="submit" type="primary">Send</a-button>
</div>
Javascript code :
data() {
return {
idStudy: this.$route.params.id,
aucuneQuestion:false,
questionsSignaletiques: [
{
"study":"/api/studies/" + this.$route.params.id,
"question":
{
type: "",
item: "",
multiple: false,
obligatoire: false,
inverse: false,
barometre: false,
originale: false,
signaletik: true,
choices: [{name:''}]
},
"error": {
message:"",
here:false
}
}
],
}
},
mounted() {
//retreive all the questions still recorded
axios
.get('http://127.0.0.1:8000/api/studies/' + this.idStudy + '/question_studies?question.signaletik=true')
.then((result)=>{
console.log(result.data["hydra:member"])
this.aucuneQuestion = result.data["hydra:member"].length === 0;
//on met les données dans le store
this.$store.commit("setListeQuestionsSignaletiques", result.data["hydra:member"])
})
.catch(err=>console.log(err))
},
methods: {
//Adding a question
addItem () {
this.questionsSignaletiques.push(
{
"study":"/api/studies/" + this.idStudy,
"question":
{
type: "",
item: "",
multiple: false,
obligatoire: false,
inverse: false,
barometre: false,
originale: false,
signaletik: true,
choices: [{name:''}]
},
"error": {
message:"",
here:false
}
}
)
},
//adding a choice
addChoice: function(choice) {
choice.question.choices.push({
name: ''
})
},
// Sending the forms
submit () {
//loop table to retrieve all questions and indexes if the user adding several questions
this.questionsSignaletiques.forEach((element,index) =>
{
const inputType = element.question.type
const inputItem = element.question.item
const inputChoice = element.question.choices
//loop on choices to see if empty one or not
for (const oneChoice of inputChoice)
{
if ((inputChoice.length == 1) ||(inputChoice.length == 2 && oneChoice.name == ""))
{
element.error.here=true
element.error.message = "You must have two choices at least"
return false; // stop here if error
}
else
{}
}// end loop of choices
// verify other fields
if (inputType == "" || inputItem =="")
{
element.error.here=true
element.error.message = "Title and item must not be empty"
}
else
{
// everything is ok we can record in db and store
//reset fields == does not work
this.$refs['p' + index][0].fields.resetField()
//this.$refs['p' + index][0].resetFields();
// adding questions in db one by one
/*
axios
.post('http://127.0.0.1:8000/api/question_studies', element)
.then((result)=>{
console.log(result)
//add in the state
this.$store.commit("addQuestionSignaletique", element)
})
.catch(error => {
console.log("ERRRR:: ",error);
});
*/
}
}) //end loop foreach
}
}
};
Thanks a lot for help
EDIT AFTER THE FIRST ANSWER
Ok I didn't know. So I changed my mind : I added a "show" in my "data" which is true at the beginning. If everything is ok, I save the question and set the show to false.
The problem now is that when I have a question that is OK and the other one that is not. When I correct the question that was not ok and save it, BOTH questions go into the STATE. So there is a duplicate in my state AND my DB... What can I do? This is the code :
I just added this in the HTML :
<div v-for="(question, index) in questionsSignaletiques" :key="index" >
<a-form-model
layout="inline"
v-if="question.show"
class="blockQuestion"
>
...
data() {
return {
idStudy: this.$route.params.id,
aucuneQuestion:false,
questionsSignaletiques: [
{
"study":"/api/studies/" + this.$route.params.id,
"question":
{
type: "",
item: "",
multiple: false,
obligatoire: false,
inverse: false,
barometre: false,
originale: false,
signaletik: true,
choices: [{name:''}]
},
"error": {
message:"",
here:false
},
"show":true,
}
],
}
},
mounted() {
//retrieve question still recorded
axios
.get('http://127.0.0.1:8000/api/studies/' + this.idStudy + '/question_studies?question.signaletik=true')
.then((result)=>{
console.log(result.data["hydra:member"])
this.aucuneQuestion = result.data["hydra:member"].length === 0;
this.$store.commit("setListeQuestionsSignaletiques", result.data["hydra:member"])
})
.catch(err=>console.log(err))
},
methods: {
//adding a question
addItem () {
this.questionsSignaletiques.push(
{
"study":"/api/studies/" + this.idStudy,
"question":
{
type: "",
item: "",
multiple: false,
obligatoire: false,
inverse: false,
barometre: false,
originale: false,
signaletik: true,
choices: [{name:''}]
},
"error": {
message:"",
here:false
},
"show":true
}
)
},
//adding a choice
addChoice: function(choice) {
choice.question.choices.push({
name: ''
})
},
// submit the form
submit () {
this.questionsSignaletiques.forEach((element,index) =>
{
const inputType = element.question.type
const inputItem = element.question.item
const inputChoice = element.question.choices
for (const oneChoice of inputChoice)
{
if ((inputChoice.length == 1) ||(inputChoice.length == 2 && oneChoice.name == ""))
{
element.error.here=true
element.error.message = "You must have two choices at least"
return false; //on s'arrête là si il y a une erreur
}
else
{
console.log("no problem")
}
}
if (inputType == "" || inputItem =="")
{
element.error.here=true
element.error.message = "You must fill type and item"
}
else
{
// hide the question form
element.show =false
//adding in db
axios
.post('http://127.0.0.1:8000/api/question_studies', element)
.then((result)=>{
//add in the state
this.$store.commit("addQuestionSignaletique", element)
})
.catch(error => {
console.log("ERRRR:: ",error);
});
}
}) //end loop foreach
}
}
};
Thanks for help !
form.reset() does not work when using v-model.
Reset the reactive data instead.
reset() {
this.question.question.type = ""
...
...
}

Gijgo Grid doesn't bind data if I call action from ajax

I am using gijgo grid to bind data. I did it two ways using gijgo grid.
1)First Binding data with html helpers to html table and doing CRUD with Gijgo,it binds data,do CRUD but does not reload grid on add,edit and delete.
<table id="grid">
<thead>
<tr>
<th width="56">ID</th>
<th data-sortable="true">Brand</th>
<th data-sortable="true">Model</th>
<th width="64" data-tmpl="<span class='material-icons gj-cursor-pointer'>edit</span>" align="center" data-events="click: Edit"></th>
<th width="64" data-tmpl="<span class='material-icons gj-cursor-pointer'>delete</span>" align="center" data-events="click: Delete"></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Id)
</td>
<td>
#Html.DisplayFor(modelItem => item.Brand)
</td>
<td>
#Html.DisplayFor(modelItem => item.Model)
</td>
</tr>
}
</tbody>
</table>
in delete function,grid doesn't reload after deleting
function Delete(e) {
if (confirm('Are you sure?')) {
$.ajax({ url: '/Home/Delete', data: { id: e.data.id }, method: 'POST' })
.done(function () {
//grid.reload({ page: 1});
grid.reload();
})
.fail(function () {
alert('Failed to delete.');
});
}
}
2) Then I did a different implementation of gijgo grid binding data via ajax call of gijgo using this example
Gijgo Grid example
The Get function returns JSON
public JsonResult Get(int? page, int? limit, string sortBy, string direction, string brand, string model)
{
List<CarsViewModel> records;
int total;
var query = _context.Cars.Select(p => new CarsViewModel
{
Id = p.Id,
Brand = p.Brand,
Model = p.Model
});
if (!string.IsNullOrWhiteSpace(model))
{
query = query.Where(q => q.Model != null && q.Model.Contains(model));
}
if (!string.IsNullOrWhiteSpace(brand))
{
query = query.Where(q => q.Brand != null && q.Brand.Contains(brand));
}
if (!string.IsNullOrEmpty(sortBy) && !string.IsNullOrEmpty(direction))
{
if (direction.Trim().ToLower() == "asc")
{
switch (sortBy.Trim().ToLower())
{
case "brand":
query = query.OrderBy(q => q.Brand);
break;
case "model":
query = query.OrderBy(q => q.Model);
break;
}
}
else
{
switch (sortBy.Trim().ToLower())
{
case "brand":
query = query.OrderByDescending(q => q.Brand);
break;
case "model":
query = query.OrderByDescending(q => q.Model);
break;
}
}
}
//else
//{
// query = query.OrderBy(q => q.o);
//}
total = query.Count();
if (page.HasValue && limit.HasValue)
{
int start = (page.Value - 1) * limit.Value;
records = query.Skip(start).Take(limit.Value).ToList();
}
else
{
records = query.ToList();
}
return this.Json(new { records, total }, JsonRequestBehavior.AllowGet);
}
jQuery(document).ready(function ($) {
grid = $('#grid').grid({
primaryKey: 'Id',
dataSource: '/Home/Get',
columns: [
{ field: 'Id', width: 56 },
{ field: 'Brand', sortable: true },
{ field: 'Model', sortable: true },
{ width: 64, tmpl: '<span class="material-icons gj-cursor-pointer">edit</span>', align: 'center', events: { 'click': Edit } },
{ width: 64, tmpl: '<span class="material-icons gj-cursor-pointer">delete</span>', align: 'center', events: { 'click': Delete } }
],
pager: { limit: 5 }
});
dialog = $('#dialog').dialog({
autoOpen: false,
resizable: false,
modal: true,
width: 360
});
$('#btnAdd').on('click', function () {
$('#Id').val('');
$('#Brand').val('');
$('#Model').val('');
dialog.open('Add Car');
});
$('#btnSave').on('click', Save);
$('#btnCancel').on('click', function () {
dialog.close();
});
$('#btnSearch').on('click', function () {
grid.reload({ page: 1, name: $('#txtBrand').val(), nationality: $('#txtModel').val() });
});
$('#btnClear').on('click', function () {
$('#txtBrand').val('');
$('#txtModel').val('');
grid.reload({ brand: '', model: '' });
});});
which results in JSON returned in this format
{"records":[{"Id":7,"Brand":"toyota","Model":"matrix"},{"Id":8,"Brand":"Mazda","Model":"M3"}],"total":2} and gives error unable to bind data like
SyntaxError: Unexpected token o in JSON at position 1
If I remove the record and total section and put raw json as datasource like this
[{"Id":7,"Brand":"toyota","Model":"matrix"},{"Id":8,"Brand":"Mazda","Model":"M3"}]
then data is bound but again grid.reload() doesnt work. I am really frustrated why this issues are there. First the gijgo grid server side controller code returns JSON dataas record with total and then I am not able to bind it with the code that gijgo has provided in jquery. Then grid.reload() isn't working
Could you review our ASP.NET examples where everything is setup correctly. You can find them at https://github.com/atatanasov/gijgo-asp-net-examples

controller to populate the data into the datatable using angular js

I want to populate the data into the datatable but no data is getting populated into the table.
Error I'm getting on debugging is:
Uncaught TypeError: Cannot read property 'getContext' of null
html:
<table class="display table table-bordered table-striped" id="example">
<thead>
<tr>
<th>User Name</th>
<th>Email Id</th>
<th>Group Name</th>
<th>Created Date</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in items">
<td>{{item.user}}</td>
<td>{{item.email}}</td>
<td>{{item.groupName}}</td>
<td>{{item.createdAt}}</td>
</tr>
</tbody>
</table>
controller:
(function () {
"use strict";
angular.module('app').controller('superAdminController', function ($scope, AuthenticationService, $timeout, $location, $http, myConfig) {
AuthenticationService.loadSuperAdmin(function (response) {
if (response.data.success) {
$scope.populateTable(response.data);
console.log(response.data);
} else {
$scope.items = [];
}
});
$scope.populateTable = function (data) {
$scope.items = data.loadSuperAdminData;
$timeout(function () {
$("#example").dataTable();
}, 200)
};
});
}());
In controller, you can populate your server response like this.
$.post(MY_CONSTANT.url + '/api_name',{
access_token: accessToken
}).then(
function(data) {
var dataArray = [];
data = JSON.parse(data);
var lst = data.list;
lst.forEach(function (column){
var d = {user: "", email: "", group: "", created: ""};
d.user = column.user;
d.email = column.email;
d.groupName = column.group;
d.createdAt = column.created;
dataArray.push(d);
});
$scope.$apply(function () {
$scope.list = dataArray;
// Define global instance we'll use to destroy later
var dtInstance;
$timeout(function () {
if (!$.fn.dataTable) return;
dtInstance = $('#datatable4').dataTable({
'paging': true, // Table pagination
'ordering': true, // Column ordering
'info': true, // Bottom left status text
// Text translation options
// Note the required keywords between underscores (e.g _MENU_)
oLanguage: {
sSearch: 'Search all columns:',
sLengthMenu: '_MENU_ records per page',
info: 'Showing page _PAGE_ of _PAGES_',
zeroRecords: 'Nothing found - sorry',
infoEmpty: 'No records available',
infoFiltered: '(filtered from _MAX_ total records)'
}
});
var inputSearchClass = 'datatable_input_col_search';
var columnInputs = $('tfoot .' + inputSearchClass);
// On input keyup trigger filtering
columnInputs
.keyup(function () {
dtInstance.fnFilter(this.value, columnInputs.index(this));
});
});
// When scope is destroyed we unload all DT instances
// Also ColVis requires special attention since it attaches
// elements to body and will not be removed after unload DT
$scope.$on('$destroy', function () {
dtInstance.fnDestroy();
$('[class*=ColVis]').remove();
});
});
});

Reloading DataTable.js fnServer fnDraw

First I initiate all datatables by the following code (there are more options, but I'm adding a minimum for this example). The code bellow is working and start all datatables, if the datatable has a search, it'll initialise the fnServerParams with the parameters. (the parameters are going to the function on the codebehind and working).
var dt = jQuery(".dataTable");
if(jQuery().dataTable && dt.length > 0) {
dt.each(function () {
var e = {
sPaginationType: "full_numbers",
};
// If has external filters
if(!!jQuery(this).data("searchbox")) {
var search_box = jQuery(jQuery(this).data("searchbox"));
var additional_filters = [];
jQuery.each(search_box.find('input,select'), function(i, v){
additional_filters.push({
name: jQuery(v).attr('name'),
value: jQuery(v).val()
});
});
if (additional_filters.length > 0) {
e.fnServerParams = function (aoData) {
for (var i=0; i < additional_filters.length; i++) {
var filter = additional_filters[i];
aoData.push( { "name": filter.name, "value": filter.value } );
}
}
}
}
jQuery(this).dataTable(e);
});
}
The problem is when I call my function RefreshDataTables() by a click/change event. In the function I used this simplified version to refresh:
PS: All code below is to be interpreted that is inside RefreshDataTables()
var dt = jQuery(".dataTable");
if(jQuery().dataTable && dt.length > 0) {
dt.each(function () {
var $oTable = jQuery(this).dataTable();
$oTable.fnDraw();
});
}
But it doesn't update the changes on the inputs/selects of the search. it keep the same from the before. So I tried this code base on this answer:
var dt = jQuery(".dataTable");
if(jQuery().dataTable && dt.length > 0) {
dt.each(function () {
var $oTable = jQuery(this).dataTable();
var search_box = jQuery(jQuery(this).data("searchbox"));
var additional_filters = [];
jQuery.each(search_box.find('input,select'), function(i, v){
additional_filters.push({
name: jQuery(v).attr('name'),
value: jQuery(v).val()
});
});
if (additional_filters.length > 0) {
$oTable._fnServerParams = function (aoData) {
for (var i=0; i < additional_filters.length; i++) {
var filter = additional_filters[i];
aoData.push( { "name": filter.name, "value": filter.value } );
}
}
}
$oTable.fnDraw();
});
}
But it didn't work. There is no error, but the data is still the same, without any change.
You're querying values of INPUT and SELECT only once during initialization. Instead you should do it every time the data is requested from the server.
So you can modify your initialization code so that you retrieve INPUT and SELECT values on every call to function defined with fnServerParams.
Below I just moved your code into fnServerParams callback.
var dt = jQuery(".dataTable");
if(jQuery().dataTable && dt.length > 0) {
dt.each(function () {
var e = {
sPaginationType: "full_numbers",
fnServerParams: function(aoData){
// If has external filters
if(!!jQuery(this).data("searchbox")) {
var search_box = jQuery(jQuery(this).data("searchbox"));
var additional_filters = [];
jQuery.each(search_box.find('input,select'), function(i, v){
additional_filters.push({
name: jQuery(v).attr('name'),
value: jQuery(v).val()
});
});
if (additional_filters.length > 0) {
for (var i=0; i < additional_filters.length; i++) {
var filter = additional_filters[i];
aoData.push( { "name": filter.name, "value": filter.value } );
}
}
}
}
};
jQuery(this).dataTable(e);
});
}
Then your RefreshDataTables() calling $oTable.fnDraw() should work.
See the example below for code and demonstration. Please note, that I'm using jQuery Mockjax plug-in just for the sake of demonstrating Ajax request, it's not needed for production code.
$(document).ready(function() {
// AJAX emulation for demonstration only
$.mockjax({
url: '/test/0',
responseTime: 200,
response: function(settings) {
console.log("Request data: ", settings.data);
this.responseText = {
"aaData": [
[
"Trident",
"Internet Explorer 4.0",
"Win 95+",
"4",
"X"
],
[
"Trident",
"Internet Explorer 5.0",
"Win 95+",
"5",
"C"
],
[
"Trident",
"Internet Explorer 5.5",
"Win 95+",
"5.5",
"A"
]
]
};
}
});
$('#example').dataTable({
"sAjaxSource": "/test/0",
"bServerSide": true,
"fnServerParams": function(aoData) {
// If has external filters
if (!!jQuery(this).data("searchbox")) {
var search_box = jQuery(jQuery(this).data("searchbox"));
var additional_filters = [];
jQuery.each(search_box.find('input,select'), function(i, v) {
additional_filters.push({
name: jQuery(v).attr('name'),
value: jQuery(v).val()
});
});
if (additional_filters.length > 0) {
for (var i = 0; i < additional_filters.length; i++) {
var filter = additional_filters[i];
aoData.push({
"name": filter.name,
"value": filter.value
});
}
}
}
}
});
$('#btn').on('click', function(){
$('#example').dataTable().fnDraw();
});
});
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<link href="//cdn.datatables.net/1.9.4/css/jquery.dataTables.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="//cdn.datatables.net/1.9.4/js/jquery.dataTables.min.js"></script>
<script src="http://vitalets.github.com/x-editable/assets/mockjax/jquery.mockjax.js"></script>
</head>
<body>
<p id="searchbox">
<input type="text" name="param1" value="" placeholder="param1">
<button id="btn" type="button">Search</button>
</p>
<table cellpadding="0" cellspacing="0" border="0" class="display" id="example" data-searchbox="#searchbox">
<thead>
<tr>
<th width="20%">Rendering engine</th>
<th width="25%">Browser</th>
<th width="25%">Platform(s)</th>
<th width="15%">Engine version</th>
<th width="15%">CSS grade</th>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
<tr>
<th>Rendering engine</th>
<th>Browser</th>
<th>Platform(s)</th>
<th>Engine version</th>
<th>CSS grade</th>
</tr>
</tfoot>
</table>
</body>
</html>

how to get id from webgrid with javascript

i try to make webgrid and when i click edit button, the button will pass value from first td in webgrid to my controller, but i cant pass the value.. can some one tell me, what line is error?
this my view
#grid.GetHtml(
tableStyle: "grid",
headerStyle: "head",
alternatingRowStyle: "alt",
firstText: "<< First",
previousText: "< Prev",
nextText: "Next >",
lastText: "Last >>",
mode: WebGridPagerModes.All,
columns: grid.Columns(
grid.Column(header: "Content ID", format: (item) => item.ContentID),
grid.Column(header: "Active", format: (item) => Html.Raw("<input type=\"checkbox\" " + ((item.Active == true) ? "checked='cheked'" : "") + "disabled = 'disabled'/>")),
grid.Column(header: "Image", format: #<img src="#Href("~/images/MobileContent/" + #item.ImageURL)" width="120px" height="50px;" />),
grid.Column("Description"),
grid.Column("Action", format: #<text>
<button class="edit-content">Edit</button>
<button class="remove-content">Remove</button>
</text>)
)
)
}
</div>
</div>
</div>
</div>
</div>
</div>
#section scripts{
<script>
$(".edit-content").click(function () {
var id = $(this).find('td:first').text();
location.href = '/MobileContent/Edit/' + id;
});
$('thead tr th:nth-child(1), tbody tr td:nth-child(1)').hide();
</script>
}
this my controller
public ActionResult Edit(int id)
{
ViewModel.MobileContent.MobileContentViewModel vm = new ViewModel.MobileContent.MobileContentViewModel();
vm.EditContent = EditContent(id);
return View(vm);
}
Have a try
var id = $(this).parent('tr').find('td:first').text();
Try this,
<input type="button" value="Assign" onclick="myfunction(#item.ID);" />
OR
#Html.ActionLink("EditUser", "DYmanicControllerPage", "Test", new { Id = item.ID }, new { #class = "hide" })
function myfunction(obj) {
var id = obj;
location.href = '#Url.Action("DYmanicControllerPage", "Test")?Id=' + id;
}
Controller
public ActionResult DYmanicControllerPage(string Id)
{
var model = new RegisterModel();
int _ID = 0;
int.TryParse(Id, out _ID);
if (_ID > 0)
{
RegisterModel register = GetRegisterUserById(_ID);
model.ID = _ID;
model.Name = register.Name;
model.Address = register.Address;
model.PhoneNo = register.PhoneNo;
}
return View(model);
}

Categories