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 dataTable in strongly typed Razor View Page.Now as per my requirement I need to populate this with my Model of the page but i am not getting how to do it.Here is my dataTable Code..
$(document).ready(function () {
var dt;
var dataSet = [];
dt = $("#Setup").dataTable({
"data": dataSet,
"paging": false,
"responsive": true,
"stateSave": true,
"columns": [
{ "title": "<input type='checkbox' id='selectAll'>", "bSortable": false, "width": "5px", },
{ "title": "", "bSortable": false, "width": "5px" },
{ "title": "Code", "width": "50px" },
{ "title": "Name" }
]
});
});
My page is Razor View Page .Please help me to get it done..Thanks..
Generally you should be able to inline your data from razor like this:
#{
StringBuilder sb = new StringBuilder();
foreach(row in model.MyTable)
{
sb.AppendFormat("['{0}', '{1}', '{2}', '{3}'],",
row.Field1, row.Field2, row.Field3, row.Field4);
}
}
$(document).ready(function () {
var dt;
var dataSet = [#Html.Raw(sb.ToString(0, sb.Length - 1))];
dt = $("#Setup").dataTable({
"data": dataSet,
"paging": false,
"responsive": true,
"stateSave": true,
"columns": [
{ "title": "<input type='checkbox' id='selectAll'>", "bSortable": false, "width": "5px", },
{ "title": "", "bSortable": false, "width": "5px" },
{ "title": "Code", "width": "50px" },
{ "title": "Name" }
]
});
});
You should use sb.Length - 1 in order to remove the last comma (,) from the output array. Using Html.Raw() prevents Razor from encoding the string which would ruin the JavaScript syntax.
It's easier: "data": #Html.Raw(Json.Encode(Model.MyList)) - For me it works.
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 am new to C# and ASP.NET MVC and specially views.
I have the following problem
I have this code
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult ManageEmployee(int cntID, string command)
{
//repository = new ContactRepository();
cntadrRepository = new ContactAddressCountryRepository();
//addressRepository = new AddressRepository();
if (!String.IsNullOrEmpty(command) && command.Equals("edit"))
{
var cdrcnts = cntadrRepository.GetById(cntID);
ViewBag.IsUpdate = true;
//return View("_ManageEmployee", cdrcnts);
return View("Index", cdrcnts);
//return View("Index");
}
else
{
ViewBag.IsUpdate = false;
//return View("_ManageEmployee");
return View("Index");
}
}
that returns my form empty when I click on Add button
when I click on Add I get the form slide in and the grid slide out and I can enter a new record and then after clicking on save I return to my grid with the new record.
Now the problem is When I click on Edit I have the view with only an Add button that when I click on I get the result that I want to get, directly, when I click on Edit which is the form filled with the required information
I think that I have a problem when I return the view.
What I want is that I return that form populated with the contact information when I click on Edit and stay in the same page that shows again the grid and the edited record and not have that empty page with the Add button that I need to click on again to have the required result.
Thank you for your help.
<script type="text/javascript">
$.ig.loader({
scriptPath: './js/',
cssPath: './css/',
resources: 'igGrid.*',
ready: function () {
$.getJSON("Home/GetAll", null, function (data) {
var headerTextValues = ["Relation to Will maker", "First Name", "Last Name","","",""];
$('#employeeGrid').igGrid({
expandCollapseAnimations: true,
animationDuration: 1000,
expandTooltip: "Expand to View Details",
collapseTooltip: "Hide details",
height: "400px",
width: "800px",
dataSource: data,
responseDataKey: "Records",
//dataSourceType: "json",
autoGenerateLayouts: false,
autoGenerateColumns: false,
rowEditDialogContainment: "owner",
showReadonlyEditors: false,
columns: [
{ headerText: headerTextValues[0], key: "cntID", width: 200 },
{ headerText: headerTextValues[1], key: "cntFirstName", width: 175 },
{ headerText: headerTextValues[2], key: "cntLastName", width: 175 },
//{ headerText: headerTextValues[3], key: "Age", width: 175 },
{ headerText: headerTextValues[4], key: "UpdateRow", width: 110, template: "<a href='Home/ManageEmployee?cntID=${cntID}&command=edit' class='editDialog'>Edit</a>" },
{ headerText: headerTextValues[5], key: "DeleteRow", width: 50, template: "<a href='Home/Delete?cntID=${cntID}' class='confirmDialog'><button>Delete</button></a>" },
],
initialDataBindDepth: -1,
primaryKey: 'cntID',
width: '800',
updateURL: "Home/Update",
/*columnLayouts: [
{
key: "cntD",
responseDataKey: "Records",
autoGenerateColumns: false,
autoGenerateLayouts: false,
generateCompactJSONResponse: false,
primaryKey: "cntID",
foreignKey: "cntAddressID",
columns: [
{ key: "cntId", headerText: "Address Id", width: "150px" },
{ key: "cntAddressID", headerText: "Address", width: "150px" },
//{ key: "Street", headerText: "Street", width: "150px" },
//{ key: "City", headerText: "City", width: "150px" },
//{ key: "Zip", headerText: "Zip", width: "150px" }
]
}
],*/
features: [
{
name: "Selection",
mode: "row",
multipleSelection: false
},
{
name: 'Hiding'
},
{
name: 'Paging',
type: 'local',
pageSize: 10,
inherit: true
},
{
name: 'Filtering'
},
{
name: "ColumnMoving",
mode: "immediate",
//columnDragStart: function (event, ui) {
// ui.owner.element.find('tr td:nth-child(' + (ui.columnIndex + 1) + ')').addClass("ui-state-moving");
// colMovingKey = ui.columnKey;
//},
//columnDragEnd: function (event, ui) {
// var grid = $(event.target).data('igGrid');
// var newindex = grid.options.columns.indexOf(grid.columnByKey(colMovingKey)) + 1;
// grid.element.find('tr td:nth-child(' + newindex + ')').removeClass("ui-state-moving");
//},
addMovingDropdown: true,
mode: "deferred",
type: "render"
}
],
});
});
}
});
$(document).ready(function () {
$.ajaxSetup({ cache: false });
$(".editDialog").live("click", function (e) {
e.preventDefault();
var url = $(this).attr('href');
$("#dialog-edit").load(url);
$("#dialog-edit").toggle("slide");
});
$("#openDialog").live("click", function (e) {
e.preventDefault();
var url = $(this).attr('href');
$("#dialog-create").load(url);
$("#dialog-create").toggle("slide");
})
});
</script>
#section featured {
<section class="featured">
<div class="overlap">
<div class="content-wrapper">
<!-- the igHierarchicalGrid target element-->
<table id="employeeGrid" style="width: auto;"></table>
<p>
<a id='openDialog' href='Home/ManageEmployee?cntID=0&command=create' class='openDialog ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only' style="color: white;">Add Employee</a>
</p>
<div id="btn">
<button id="add">Add</button>
</div>
i got a view with a jquery datatable, i want on a single button to repopulate the data from the table instantly with another Json list or whatever array he received from the controller.
This is the code in my view :
$.ajax({
type: "GET",
url: "EmpTruck/getJson/",
data: { search: station },
dataType: "Json",
error: function (xhr, status, error) {
alert(error);
},
success: function (json) {
alert(json.aaData);
var table = $(".dynamicTableEmployee").dataTable();
table.fnClearTable();
table.LoadDataRow(json);
}
});
This is the code from controller :
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult getJson()
{
List<Employees> list = new List<Employees>();
list = db.Employees.Where(c => c.Station.Equals("ATL")).ToList();
return this.Json(list, JsonRequestBehavior.AllowGet);
}
This code only clear the datatable.
I have set a breakpoint to see if there is something in the Json array and there is.
I don't know how to populate the datatable from the json array, do i need to serialize it ? Do the json need to be the same size as the datatable?
Thanks
If you are just looking to reload the data you can use the fnReloadAjax() API plug-in: http://datatables.net/plug-ins#api_fnReloadAjax
If you want to completely alter the table like change columns etc... I'd just nuke the old one and replace it with the new. Just paste the code into your script (before you initialise you table!), then whenever you want to reload the data, call fnReloadAjax() on the table object.
This example might help: http://datatables.net/examples/example_plugin_api.html
(from http://www.datatables.net/forums/discussion/52/load-new-data-via-ajax/p1)
<link href="#Url.Content("~/Content/Table.css")" rel="stylesheet" type="text/css" />
#section scripts
{
<script src="#Url.Content("~/Scripts/ datatable.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/test.js")" type="text/javascript"> </script>
}
<div id="tabs-SecDeal" style=" background-color: white">
<table id="secdeal" class="display">
<thead>
<tr>
<th style="background-color: #990033">col1</th>
<th style="background-color: #990033"> col2</th>
<th style="background-color: #990033"> col3 </th>
<th style="background-color: #990033"> col4</th>
</tr>
</thead>
<tbody>
<tr>
<td colspan="4" class="dataTables_empty"></td>
</tr>
</tbody>
</table>
</div>
$(function () {
Loadtestview();
function Loadtestview () {
var divSecTable = $('#secdeal');
oSecTable = divSecTable.dataTable({
"processing": true,
"serverSide": true,
"aaSorting": [1, 'asc'],
"info": true,//localtable.bInfo,
"autoWidth": false,//localtable.AutoWidth,
"scrollY": 700,
"scrollX": "150%",
"scrollCollapse": true,
'destroy': true,
"pagingType": "full_numbers",
'lengthChange': false,
"searching": false,
'sAjaxSource': '../ReportsMvc/GetSecuritizationDeal',
"iDisplayLength": 100,
"columns": [
{ "targets": 0,"data":"col1","title":"col1", "className": "center textNoWrap" },
{ "targets": 1,"data":"col2","title":"col2", "className": "center textNoWrap" },
{ "targets": 2,"data":"col3","title":"col3", "className": "center textNoWrap" },
{ "targets": 3,"data":"col4","title":"col4", "className": "center textNoWrap" },
],
'fnServerData': function (sSource, aoData, fnCallback) {
aoData.push({ "name": "rgid", "value": $("#ddlBatchdate").val() });
$.get(sSource, aoData, function (rsp) {
fnCallback(rsp);
});
},
"fnInitComplete": function () {
new $.fn.dataTable.FixedColumns(oSecTable, { leftColumns: 4 });
}
});
}
});
[HttpGet]
public JsonResult GetSecuritizationDeal(jQueryDataTableParamModel param)
{
if (param.rgid <= 0)
{
return Json(new
{
sEcho = "1",
iTotalRecords = 0,
iTotalDisplayRecords = 0,
aaData = (IEnumerable<SecDealDatacs>)new List<SecDealDatacs>()
},
JsonRequestBehavior.AllowGet);
}
try
{
//No session cache for reports page!!!
List<SecDealDatacs> listObj = _bao.GetSecuritizationDeal(param.rgid);
if (listObj == null)
throw new HttpException(500, "Data Server Errors...");
int totalRecords = listObj.Count();
//Pagenation
IEnumerable<SecDealDatacs> listObjDisplay = listObj
.Skip(param.iDisplayStart)
.Take(param.iDisplayLength);
var result = listObjDisplay.Select((o, index) => new
{
o.col1,
o.col2,
col3= o.col3.ToString("#,#"),
col4=o. col4.ToString("0.0000"),
}).ToList();
var listObj1 = result;
return Json(new
{
sEcho = param.sEcho,
iTotalRecords = totalRecords,
iTotalDisplayRecords = totalRecords,
aaData = result
},JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
//log error into DB and File
throw new HttpException(500, ex.Message);
}
}
$(function () {
Loadtestview();
function Loadtestview () {
var divSecTable = $('#secdeal');
oSecTable = divSecTable.dataTable({
"processing": true,
"serverSide": true,
"aaSorting": [1, 'asc'],
"info": true,//localtable.bInfo,
"autoWidth": false,//localtable.AutoWidth,
"scrollY": 700,
"scrollX": "150%",
"scrollCollapse": true,
'destroy': true,
"pagingType": "full_numbers",
'lengthChange': false,
"searching": false,
'sAjaxSource': '../ReportsMvc/GetSecuritizationDeal',
"iDisplayLength": 100,
"columns": [
{ "targets": 0,"data":"col1","title":"col1", "className": "center textNoWrap" },
{ "targets": 1,"data":"col2","title":"col2", "className": "center textNoWrap" },
{ "targets": 2,"data":"col3","title":"col3", "className": "center textNoWrap" },
{ "targets": 3,"data":"col4","title":"col4", "className": "center textNoWrap" },
],
'fnServerData': function (sSource, aoData, fnCallback) {
aoData.push({ "name": "rgid", "value": $("#ddlBatchdate").val() });
$.get(sSource, aoData, function (rsp) {
fnCallback(rsp);
});
},
"fnInitComplete": function () {
new $.fn.dataTable.FixedColumns(oSecTable, { leftColumns: 4 });
}
});
}
});