Related
<script>
$(function () {
#{
var rootGroup = Model.Groups.FirstOrDefault(group => group.ParentGroupId == null);
}
let selectedGroup = "";
let selectedNode = null;
let groups = {};
#foreach(var group in Model.Groups) {
#:groups["#group.GroupId"] = { delete:false ,id: "#group.GroupId", parent: "#group.ParentGroupId", name: "#group.Title", order: "#group.OrderNum" };
}
$('#groupTree').jstree({
"checkbox": { "three_state": false },
"core": {
"check_callback": true,
'data': [
#foreach (var item in Model.Groups) {
#if (item.ParentGroupId == null)
{
#:{ "id": "#item.GroupId", "parent": "#", "text": "#item.Title", "state": { "disabled": true } },
}
else
{
#:{ "id": "#item.GroupId", "parent": "#item.ParentGroupId", "text": "#item.Title" },
}
}
],
"themes": {
"icons": false
},
},
"plugins": ["themes","dnd"]
}).on('loaded.jstree', function () {
$("#groupTree").jstree("open_all");
}).on("select_node.jstree", function (evt, data) {
$("#group-name-input").val(groups[data.node.id].name);
selectedGroup = data.node.id;
selectedNode = data.node;
$("#group-name-input").prop('disabled', false);
$("#save-group-button").prop('disabled', false);
$("#delete-group-button").prop('disabled', false);
}).on("move_node.jstree", function (evt, data) {
groups[data.node.id].parent = data.parent;
groups[data.node.id].order = data.position;
$("#SerializedGroupInformation").val(JSON.stringify(groups));
})
$("#save-group-button").click(function () {
if (selectedGroup != "") {
groups[selectedGroup].name = $("#group-name-input").val();
$("#groupTree").jstree('rename_node', selectedNode, $("#group-name-input").val());
$("#SerializedGroupInformation").val(JSON.stringify(groups));
$("#group-name-input").prop('disabled', true);
$("#save-group-button").prop('disabled', true);
$("#delete-group-button").prop('disabled', true);
$("#group-name-input").val("");
}
})
$("#delete-group-button").click(function () {
if (selectedNode.children.length > 0) {
swal({
title: 'Error!',
text: 'The group can not have any children.',
icon: 'error'
});
return;
}
groups[selectedGroup].delete = true;
$("#groupTree").jstree('delete_node', selectedNode);
$("#SerializedGroupInformation").val(JSON.stringify(groups));
$("#group-name-input").prop('disabled', true);
$("#save-group-button").prop('disabled', true);
$("#delete-group-button").prop('disabled', true);
$("#group-name-input").val("");
})
$("#new-group-button").click(function () {
var name = $("#new-group-input").val();
var group = { name: name, order: "0", id: "", parent:"" }
var node = { id: name, text: name };
$('#groupTree').jstree('create_node', "#rootGroup.GroupId", node, 'last');
groups[name] = group;
$("#SerializedGroupInformation").val(JSON.stringify(groups));
$("#group-name-input").prop('disabled', true);
$("#save-group-button").prop('disabled', true);
$("#delete-group-button").prop('disabled', true);
$("#group-name-input").val("");
$("#new-group-input").val("");
})
});
</script>
Considering the code above, How could I add the new group as a child to the selected parent node? I have failed at doing so. Can anyone help? I am new to development and I hate to admit that JS is not my strong suit...yet :)
I have tried multiple things and will continue to do so, but this is the original code without my attempts at solving this. Thanks in advance!
Here is a demo to show how to add new item to selected parent:
View:
<div id="jstree">
</div>
<button id="create">create button</button>
Js code:
#section scripts{
<script src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/jstree.min.js"></script>
<script type="text/javascript">
$(function () {
var managerTeam = [{
"id": "m1",
"text": "M1",
"children": [{
"id": "m2",
"parent": "m1",
"text": "M2"
}, {
"id": "t1",
"parent": "m1",
"text": "T1"
}, {
"id": "m3",
"parent": "m1",
"text": "M3",
"children": [{
"id": "t2",
"parent": "m3",
"text": "T2"
}, {
"id": "t3",
"parent": "m3",
"text": "T3"
}],
"state": { "opened": true }
}],
"state": { "opened": true }
}];
$('#create').on('click', function () {
var position = 'inside';
var newNode = { state: "open", data: "New nooooode!" };
var parent = $('#jstree').jstree('get_selected')[0];
$('#jstree')
.jstree({
"core": {
"check_callback": true
}
})
.create_node(parent, newNode, position, false, false);
});
});
</script>
}
result:
I have a stored procedure that equates and gets the occupancy rate of a room. I want to fetch the data from the back-end using JSon and display the output data of the stored procedure in the front-end code. But the output data only sticks at the Business Layer. How can i call it from my Controller using Json?
Here is my code
In my Controller
public JsonResult GetoccupancyRate()
{
string _connectionString = rAppSetting.ConnectionString;
try
{
IList<Hotel> _currentOccupancyRateList = rHotelFacade.GetOccupancyRate(HotelIDCookie, DateTime.Now, _connectionString);
IList<Hotel> _yesterdayOccupancyRateList = rHotelFacade.GetOccupancyRate(HotelIDCookie, DateTime.Now.AddDays(-1), _connectionString);
return Json(new
{
success = true,
message = "Success",
yesterdayOccupancyRate = _yesterdayOccupancyRateList,
currentOccupancyRate = _currentOccupancyRateList
},JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return Json(new
{
success = false,
message = ex.Message,
currentOccupancyRate = "",
yesterdayOccuoancyRate = ""
}, JsonRequestBehavior.AllowGet);
}
}
Javascript
myapp.factory("occupancyRateService", ['$http', function ($http) {
this.LoadOccupancyRate = function () {
return $http.get("/Dashboard/GetOccupancyRate", {});
};
return this;}]);
myapp.controller('MainController', ['$scope', 'dashboardService', 'occupancyRateService', function ($scope, dashboardService, occupancyRateService) {
$scope.myChart = {
type: 'google.charts.Bar',
options: {},
data: {}
};
$scope.loadOccupancyRateDetails = function () {
occupancyRateService.LoadOccupancyRate().success(function (result) {
if (result.success)
{
var currentOccupancyRateData = result.currentOccupancyRate;
var yesterdayOccupancyRateData = result.yesterdayOccupancyRate;
console.log(result.currentOccupancyRate);
console.log(result.yesterdayOccupancyRate);
//console.log(yesterdayResultData)
if (currentOccupancyRateData || yesterdayOccupancyRateData === null)
{
google.charts.load('current', { 'packages': ['line', 'bar'] });
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Day', 'Rate'],
['Yesterday', 0],
['Today', 0]
]);
var options = {
chart: {
//title:'Occupancy Rate',
},
bars: 'vertical',
hAxis: { format: 'none', gridlines: { count: 5 } },
vAxis: { format: '.######%' },
height: 180,
//width: 100%,
colors: ['#1b9e77']
};
var chart = new google.charts.Bar(document.getElementById('chart_div'));
chart.draw(data, google.charts.Bar.convertOptions(options));
};
$(window).resize(function () {
drawChart();
});
}
else
{
google.charts.load('current', { 'packages': ['line', 'bar'] });
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Day', 'Rate'],
['Yesterday', currentOccupancyRateData],
['Today', yesterdayOccupancyRateData]
]);
//function drawChart() {
// var data = google.visualization.arrayToDataTable([ORData]);
var options = {
chart: {
//title:'Occupancy Rate',
},
bars: 'vertical',
hAxis: { format: 'none', gridlines: { count: 5 } },
vAxis: { format: '.################%' },
height: 180,
//width: 100%,
colors: ['#1b9e77']
};
var chart = new google.charts.Bar(document.getElementById('chart_div'));
chart.draw(data, google.charts.Bar.convertOptions(options));
};
$(window).resize(function () {
drawChart();
});
}
}
})
.error(function (error) {
alert(error);
})
};
$scope.loadOccupancyRateDetails();
//<--------------------------------------->
}]);
The problems is Datatables JS stays in state "processing" and the Chrome debug throws:
Uncaught TypeError: Cannot read property 'length' of undefined
The code in question that "feeds" datatables js is (data is some linq query):
var jsonData = Json(data);
return jsonData;
The response is (textual response):
[{
"TotalCredito": 1649112940.000000,
"TotalClientes": 1040,
"Balance7": 188974066.000000,
"Balance37": 25152742.000000,
"Balance67": 53268069.000000,
"Mes": 1
}, {
"TotalCredito": 1910576150.000000,
"TotalClientes": 941,
"Balance7": 332301396.000000,
"Balance37": 84407873.000000,
"Balance67": -7053061.000000,
"Mes": 2
}, {
"TotalCredito": 1852843443.000000,
"TotalClientes": 809,
"Balance7": 300589569.000000,
"Balance37": 87170595.000000,
"Balance67": 41900708.000000,
"Mes": 3
}, {
"TotalCredito": 1736522626.000000,
"TotalClientes": 747,
"Balance7": 235758479.000000,
"Balance37": 107699635.000000,
"Balance67": 60831390.000000,
"Mes": 4
}, {
"TotalCredito": 1611546395.000000,
"TotalClientes": 702,
"Balance7": 201209547.000000,
"Balance37": 59028449.000000,
"Balance67": 64171607.000000,
"Mes": 5
}, {
"TotalCredito": 1306131513.000000,
"TotalClientes": 697,
"Balance7": 552835099.000000,
"Balance37": 67349028.000000,
"Balance67": 50490441.000000,
"Mes": 6
}]
And the script function in the view is:
<script>
$(document).ready(function () {
var datatable = $('#informe').dataTable({
"language": { "url": "http://cdn.datatables.net/plug-ins/28e7751dbec/i18n/Spanish.json" },
"bFilter": false,
"processing": true,
"serverSide": true,
"ajax": {
"url": "somesupercoolurl",
"type": "POST",
"dataType": "json"
},
"columns": [
{ "data": "Balance7" },
{ "data": "Balance37" },
{ "data": "Balance67" },
{ "data": "Mes" },
{ "data": "TotalClientes" },
{ "data": "TotalCredito" }
],
});
});
Finally, the table is:
<table id="informe">
<thead>
<tr>
<th>Balance7</th>
<th>Balance37</th>
<th>Balance67</th>
<th>Mes</th>
<th>TotalClientes</th>
<th>TotalCredito</th>
</tr>
</thead>
</table>
I find it strange that while the information is properly formatted, is not able to process.
Finally, i resolve this
after seeing many examples, I noticed it's necessary include this 3 variables to json before parse the json object to datatables js; In the controller:
var totalDatos = data.Count();
var jsonData = Json(new {
iTotalDisplayRecords = totalDatos,
iTotalRecords = totalDatos,
aaData = data
});
return jsonData;
Whit this 'function', the json object is like this
{"iTotalDisplayRecords":6,"iTotalRecords":6,"aaData":[{"TotalCredito":1649112940.000000,"TotalClientes":1040,"Balance7":188974066.000000,"Balance37":25152742.000000,"Balance67":53268069.000000,"Mes":1},{"TotalCredito":1910576150.000000,"TotalClientes":941,"Balance7":332301396.000000,"Balance37":84407873.000000,"Balance67":-7053061.000000,"Mes":2},{"TotalCredito":1852843443.000000,"TotalClientes":809,"Balance7":300589569.000000,"Balance37":87170595.000000,"Balance67":41900708.000000,"Mes":3},{"TotalCredito":1736522626.000000,"TotalClientes":747,"Balance7":235758479.000000,"Balance37":107699635.000000,"Balance67":60831390.000000,"Mes":4},{"TotalCredito":1611546395.000000,"TotalClientes":702,"Balance7":201209547.000000,"Balance37":59028449.000000,"Balance67":64171607.000000,"Mes":5},{"TotalCredito":1306131513.000000,"TotalClientes":697,"Balance7":552835099.000000,"Balance37":67349028.000000,"Balance67":50490441.000000,"Mes":6}]}
The table, in the view:
<table id="informe">
<thead>
<tr>
<th>Mes</th>
<th>TotalCredito</th>
<th>TotalClientes</th>
<th>Balance7</th>
<th>Balance37</th>
<th>Balance67</th>
</tr>
</thead>
</table>
The Script is:
<script>
$(document).ready(function () {
var arrayDatos = {
'canal': $(" #ListaCanales ").val(),
'anio': $(" #ListaAnios ").val(),
'vendedorsigla': $(" #ListaVendedores ").val()
};
var datatable = $('#informe').dataTable({
"language": { "url": "http://cdn.datatables.net/plug-ins/28e7751dbec/i18n/Spanish.json" },
"bFilter": false,
"processing": true,
"serverSide": true,
"ajax": {
"url": "mensualajax",
"type": "POST",
"dataType": "json",
"data": arrayDatos
},
"columns": [
{ "data": "Mes", "bSortable": false },
{ "data": "TotalCredito" },
{ "data": "TotalClientes" },
{ "data": "Balance7" },
{ "data": "Balance37" },
{ "data": "Balance67" }
],
});
$(" #FiltrarResultados ").click(function () {
var arrayDatos = {
'canal': $(" #ListaCanales ").val(),
'anio': $(" #ListaAnios ").val(),
'vendedorsigla': $(" #ListaVendedores ").val()
};
datatable.fnClearTable();
$('#informe').dataTable({
"bDestroy": true,
"language": { "url": "http://cdn.datatables.net/plug-ins/28e7751dbec/i18n/Spanish.json" },
"bFilter": false,
"processing": true,
"serverSide": true,
"ajax": {
"url": "mensualajax",
"type": "POST",
"dataType": "json",
"data": arrayDatos
},
"columns": [
{ "data": "Mes", "bSortable": false },
{ "data": "TotalCredito" },
{ "data": "TotalClientes" },
{ "data": "Balance7" },
{ "data": "Balance37" },
{ "data": "Balance67" }
],
});
});
});
is important remark, i use the 'click' function to reload whit ajax the datatables, the 'click' function is nearly equal to the another, but i aggregate "bDestroy": true,in the datatable constructor to reload the datatables (It is not very elegant, but work).
Finally, my new superduper controller to render, capture and updating data with DatatablesJs
//repository with the query
var repositorio = new Repositorios.InformeMensualController();
//capture ajax
string canal = String.Join("", Request.Form.GetValues("canal"));
string auxAnio = String.Join("", Request.Form.GetValues("anio"));
int anio = Convert.ToInt32(auxAnio);
string auxVendedorCodigo = String.Join("", Request.Form.GetValues("vendedorsigla"));
int vendedorCodigo = Convert.ToInt32(auxVendedorCodigo);
//set up data
var data = repositorio.CargaDatos(canal, anio, vendedorCodigo);
//Transformación a JSON y Datatables JS.
var totalDatos = data.Count();
var jsonData = Json(new {
iTotalDisplayRecords = totalDatos,
iTotalRecords = totalDatos,
aaData = data});
return jsonData;
I hope this is useful to someone
regards! :)
I would like add columns dynamically in DataTables.
I retrieve an array with the values for the title of my DataTables.
For the first column, I want nothing and then I want to put my array with the values.
I use Ajax to retrieve the values for titles of DataTables in allyearstat11 .
Here is my javascript code :
function getStatistic11() {
var response;
var allstat11 = [];
var allyearstat11 = [];
var nbY = 20;
$.ajax({
type: 'GET',
url: 'http://localhost:52251/Service1.asmx/Statistic_11',
data: "nbYear='" + nbY + "'",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
response = msg.d;
for (var i = 0; i < response.Items.length; i++) {
allstat11[i] = new Array(nbY);
var j = 0;
allstat11[i][j] = response.Items[i].Interventie;
var t = 1;
while (j <= nbY) {
allstat11[i][t] = response.Items[i].Sum[j];
t++;
j++;
}
}
for (var k = 0; k <= nbY; k++) {
allyearstat11[k] = response.Items[0].YearStart + k;
}
fillDataTable11(allstat11, allyearstat11);
},
error: function (e) {
alert("error loading statistic 11");
}
});
}
Here is my javascript code that fills the DataTables, it works well but manually
function fillDataTable11(data, allyearstat11) {
if ($("#table_statistic_11").css("visibility") == "hidden")
$("#table_statistic_11").css("visibility", "visible");
$('#table_statistic_11').dataTable({
'aaData': data,
'aoColumns': [
{ "sTitle": "", "sCellType": "th", "fnCreatedCell": function (cell) { cell.scope = 'row'; } },
{ "sTitle": allyearstat11[0] },
{ "sTitle": allyearstat11[1] },
{ "sTitle": allyearstat11[2] },
{ "sTitle": allyearstat11[3] },
{ "sTitle": allyearstat11[4] },
{ "sTitle": allyearstat11[5] },
{ "sTitle": allyearstat11[6] },
{ "sTitle": allyearstat11[7] },
{ "sTitle": allyearstat11[8] },
{ "sTitle": allyearstat11[9] },
{ "sTitle": allyearstat11[10] },
{ "sTitle": allyearstat11[11] },
{ "sTitle": allyearstat11[12] },
{ "sTitle": allyearstat11[13] },
{ "sTitle": allyearstat11[14] },
{ "sTitle": allyearstat11[15] },
{ "sTitle": allyearstat11[16] },
{ "sTitle": allyearstat11[17] },
{ "sTitle": allyearstat11[18] },
{ "sTitle": allyearstat11[19] },
{ "sTitle": allyearstat11[20] }
],
"iDisplayLength": 12,
"bJQueryUI": true,
"bDestroy": true,
"bPaginate": false,
"bLengthChange": false,
"bFilter": false,
"bSort": false,
"bInfo": false,
"bAutoWidth": false
});
}
Can I use for loop in "aoColumns"?
How do I do ?
I solved the problem :
var tabTitleColumn = [];
for (var i = 0; i < allyearstat11.length; i++) {
tabTitleColumn.push({
"sTitle": allyearstat11[i],
});
};
And after :
'aoColumns': tabTitleColumn
I am using plupload flash runtime in my website to upload the files as Attachments and send them via email. The website runs fine on chrome, IE9 and IE11 but not on IE8. And most of my users are going to be using IE8. I have been trying many different things but none seemed to be working. Can anyone please suggest me any solution?
This is my javascript code where I am uploading of file takes place.
modules.compose = (function () {
"use strict";
var config = {
id: '',
requestToken: $('meta[name="__AntiForgeryToken"]').attr('content'),
runtimes: 'gears,flash,silverlight,browserplus,html5',
maxFileSize: '200mb',
maxQueueSize: 10485760,
chunkSize: '1mb',
pingFrequency: 100000,
isUploaderOpen: false
},
bindUploader = function () {
$("#uploader").pluploadQueue({
// General settings
runtimes: config.runtimes,
url: '/upload.ashx' + '?id=' + config.id,
max_file_size: config.maxFileSize,
chunk_size: config.chunkSize,
unique_names: false,
headers: { '__AntiForgeryToken': config.requestToken },
// Browse filters
filters: [
{ title: "All files", extensions: "*.*" },
{ title: "Image files", extensions: "jpg,gif,png,tiff" },
{ title: "XML files", extensions: "xml" },
{ title: "PDF documents", extensions: "pdf" },
{ title: "Zip files", extensions: "zip" },
{ title: "Text files", extensions: "txt,log" },
{ title: "Powerpoint documents", extensions: "ppt,pptx,pptm,potx,potm,ppam,ppsx,ppsm,sldx,sldm,thmx" },
{ title: "Excel documents", extensions: "xls,xlsx,xlsm,xltx,xltm,xlsb,xlam" },
{ title: "Word documents", extensions: "doc,docx,docm,dotx,dotm" },
],
preinit: {
Init: function (up, info) {
$('.plupload_header, .plupload_start').remove();
}
},
init: {
UploadProgress: function (up, file) {
bumpProgress(up, file);
},
StateChanged: function (up) {
if (up.total && up.files && up.total.uploaded === up.files.length) {
var parent = $('#upload-status').parent();
$('#upload-status').fadeOut('slow').remove();
$('#send-status').appendTo(parent).fadeIn('slow');
__doPostBack('ctl00$Content$btnSendMessage', '');
}
},
FilesAdded: function (up, files) {
var i = 0;
while (i++ < up.files.length) {
$('#btnSendMessage').removeAttr("disabled");
var ii = i;
while (ii < up.files.length) {
if (up.files[i - 1].name == up.files[ii].name) {
up.removeFile(up.files[ii]);
} else {
ii++;
}
}
}
},
QueueChanged: function (up) {
if (up.total.size > config.maxQueueSize) {
$('#upload-warning-modal').modal('show');
if (up.total.queued - 1 >= 0) {
up.removeFile(up.files[up.total.queued - 1]);
}
}
}
},
// Flash settings
flash_swf_url: '/assets/js/plupload/plupload.flash.swf',
// Silverlight settings
silverlight_xap_url: '/assets/js/plupload/plupload.silverlight.xap'
});
},
bindAddAttachments = function () {
$('#btnAddAttachments').click(function (e) {
e.preventDefault();
if (!config.isUploaderOpen) {
bindUploader();
$('#uploader').show();
config.isUploaderOpen = true;
}
$(this).attr('disabled', 'disabled');
});
},
bindSendMessage = function () {
$('#btnSendMessage').click(function (e) {
e.preventDefault();
if (!Page_ClientValidate()) {
return;
}
$('.plupload_filelist_footer').css('display', 'none');
$('#uploader').block({
message: $('#upload-status'),
css: {
padding: 0,
margin: 0,
width: '50%',
top: '50%',
left: '35%',
textAlign: 'left',
color: '#000',
border: '0',
backgroundColor: 'transparent',
cursor: 'wait'
}
});
$('input[type="text"], textarea').prop('readonly', true).addClass('disabled');
$('#btnSendMessage').button('loading');
var queue = $("#uploader").pluploadQueue();
if (queue) {
queue.start();
} else {
__doPostBack('ctl00$Content$btnSendMessage', '');
}
});
},
bumpProgress = function (up, file) {
if (up.total.percent >= 80) {
$('#upload-status .progress').removeClass('progress-info').addClass('progress-success');
}
$('#upload-status .progress .bar').css('width', up.total.percent + '%');
},
bindTextareaLimit = function () {
$('#txtMessage').limit('2000', '#charsLeft');
},
initAttachmentsButton = function () {
$('#btnAddAttachments').prop('disabled', '');
},
initPing = function () {
(function ping() {
$.get("/ping.ashx");
setTimeout(ping, config.pingFrequency);
})();
};
return {
init: function (options) {
config = $.extend({}, config, options || {});
$(function () {
initAttachmentsButton();
initPing();
bindSendMessage();
bindAddAttachments();
bindTextareaLimit();
});
},
validateRecipientEmail: function (sender, args) {
var proxy = new ServiceProxy('/Default.aspx/', { async: false });
proxy.invoke(
'IsValidRecipient',
{ recipient: $('#txtRecipient').val() },
function (result) {
return (args.IsValid = result.d);
});
},
validateSenderEmail: function (sender, args) {
var proxy = new ServiceProxy('/Default.aspx/', { async: false });
proxy.invoke(
'IsValidSender',
{ sender: $('#txtSender').val() },
function (result) {
return (args.IsValid = result.d);
});
}
};
} ());
Hope I'm not too late. Recently had the same problem. The problem is that you use
headers: { '__AntiForgeryToken': config.requestToken },
But by the specification it is not supported in HTML4 runtime:
http://www.plupload.com/docs/Options#runtimes
headers
A way to pass custom HTTP headers with each upload request. The option is simple set of key/value pairs of header names and their values.
Not supported by html4 runtime.
Requires special operational mode in case of flash and silverlight runtimes.
Since in IE8 can be disabled all other ways to upload files it will use HTML4 runtime, which doesn't have any legal way how to set antiForgery token. So your server-side will think that your sended file is not secure due it doesn't have antiForgery token and with drop with Forbidden HTTP status.
Conclusion - you are not abble to use AntiForgery token with plupload in IE8 in the how it is built in ASP.NET MVC.