JsTree one node with two parent - html

I show jstree in ui and fill it whith json from asp.net server side code ,it's work good but when i have one node with two parent its dont work well.
Could i show jstree that has one node with two parent?
when i do this its get show error.
its cut child between two parent!
I know its not tree role but i need it.
$(function () {
$('#jstree').jstree({
'core': {
"animation": 0,
"check_callback": true,
"themes": { "stripes": true },
'data': {
'url': '/Products/ProductCategoryStructure/GetData',
'data': function (node) {
return { 'id': node.id };
}
}
},
"types": {
"#": {
"max_children": 1,
"max_depth": 4,
"valid_children": ["root"]
},
"default": {
"valid_children": ["default", "file"]
},
"file": {
"icon": "glyphicon glyphicon-file",
"valid_children": []
}
},
plugins: ["contextmenu"], contextmenu: {items: customMenu}
});
$('#jstree').on('changed.jstree', function (e, data) {
var i, j, r = [];
for (i = 0, j = data.selected.length; i < j; i++) {
r.push(data.instance.get_node(data.selected[i]).text);
}
//alert('Selected: ' + r.join(', '));
// $('#event_result').html('Selected: ' + r.join(', '));
}).jstree();
});
It's Server Side Code
[HttpGet]
public ActionResult GetData()
{
var ListProductCategoryStructure = _service.GetAll();
var nodes = new List<JsTreeModel>();
//nodes.Add(new JsTreeModel() { id = "58", parent = "#", text = " مادیران مال",opened=true,icon="/assets/pages/img/mlgo.png" });
nodes.Add(new JsTreeModel() { id = "1", parent = "#", text = " مادیران مال", opened = true, icon = "/assets/pages/img/mlgo.png" });
foreach (var item in ListProductCategoryStructure)
{
nodes.Add(new JsTreeModel() { id = item.ProductCategoryId.ToString(), parent = (item.ProductParentCategoryId==65?"#": item.ProductParentCategoryId.ToString()), text = item.ProductParentCategoryTitle,icon="false" });
}
return Json(nodes, JsonRequestBehavior.AllowGet);
}
and it's result

One node can have only one parent.

Related

Ajax Response Capitalizations Rules

A was using DataTables plugin, and when displaying my columns I needed to put the first letter to LowerCase for it to recognize the property/object, e.g:
// Object name is actually: EngineeringChange.Responsible
{
title: "Responsible",
data: "engineeringChange.responsible",
className: "columnName columnHeader",
},
I just assumed the first letter would always be capitalized to LowerCase. I tried creating a new property inside EngineeringChange named ECRNumber, so I tried:
{
title: "ECR Number",
data: "engineeringChange.eCRNumber",
className: "columnName columnHeader",
},
Isn't recognized as a parameter... After a bit of searching I find out the Json response I get on AJAX it's called ecrNumber. So now I'm actually lost on which are the rules that are automatically applied to the Json Response. How does it turn ecr to LowerCase and Number to UpperCase (the N)??
Edit
Sry, can´t think of any easy way to exactly reproduce my problem on a demo
TableDesign/Creation
table = $('#tblEntries2').DataTable({
order: [[0, 'desc']],
deferRender: true,
ajax: {
url: '#Url.Action("GetEntries", "AlteracaoEngenharia")',
method: 'GET',
dataSrc: '',
beforeSend: function () {
onBegin();
$content.hide();
$loader.show();
},
complete: function (jsonResponse) {
console.log(jsonResponse);
onComplete();
$loader.hide();
$content.fadeIn();
$('#ExcelExport').show();
table.column(5).visible(false);
table.column(6).visible(false);
table.column(7).visible(false);
table.column(9).visible(false);
table.column(10).visible(false);
table.column(11).visible(false);
}
},
dom: "<'row'<'col-2'l><'col-7 text-center'B><'col-3'f>>" +
"<'row'<'col-12'tr>>" +
"<'row'<'col-5'i><'col-7'p>>",
lengthMenu: [
[10, 25, 50, 100, -1],
['10', '25', '50', '100', 'Todos'],
],
columns: [
{
title: "Id (yr-id)",
data: "creationYear",
className: "columnNumber columnHeader",
},
{
title: "ECR Number",
data: "engineeringChange.ecrNumber",
className: "columnNumber columnHeader",
},
{
title: "Criador Alteração de Engenharia",
data: "engineeringChange.responsible",
className: "columnName columnHeader",
},
...
Handler
public IActionResult GetEntries()
{
GetDataEntries();
int count = 0;
int currentYear = 0;
foreach (var entry in EntriesList)
{
EngineeringChangesListViewModel h = new EngineeringChangesListViewModel
{
EngineeringChange = entry
};
if (currentYear != entry.DataCriacao.Year)
{
count = 1;
currentYear = entry.DataCriacao.Year;
}
else
{
count++;
}
h.DeadLine = entry.FinishedGood.Week + " - " + entry.DataCriacao.Year.ToString();
if (entry.OldPart == null)
{
h.EngineeringChange.OldPart = new Part();
}
if (entry.NewPart == null)
{
h.EngineeringChange.NewPart = new Part();
}
if (entry.FinishedGood == null)
{
h.EngineeringChange.FinishedGood = new FinishedGood();
}
if (entry.OldPart != null && entry.OldPart.CDP.HasValue)
h.OldPartValue = entry.OldPart.CDP * entry.OldPart.Stock;
if (entry.NewPart != null && entry.NewPart.CDP.HasValue)
h.NewPartValue = entry.NewPart.CDP * entry.NewPart.Stock;
h.EngineeringChange.ECRNumber = entry.ECRNumber;
//toString("D4") padds the number to always be 4 digits
h.CreationYear = entry.DataCriacao.Year.ToString() + "_" + count.ToString("D4");
h.IdYear = count;
EntriesListaViewModel.Add(h);
}
var errorsJson = JsonConvert.SerializeObject(EntriesListaViewModel);
Console.WriteLine(errorsJson);
return new JsonResult(EntriesListaViewModel);
}
HANDLER OUTPUT
[{"CreationYear":"2021_0001","IdYear":1,"OldPartValue":null,"NewPartValue":2061.09155,"DeadLine":"15 - 2021","EngineeringChange":{"Id":8,"DataCriacao":"2021-03-11T16:15:24.6630956","Responsible":"José António","ECRNumber":"X1232","State":"Aberto","Comment":"Teste","UserId":1,"User":null,"Component":null,"FinishedGood":{"Id":31,"Week":15,"EngineeringChangeId":8},"OldPart":{"Id":5,"Reference":"FS12848AC","Stock":null,"CDP":1.43584776,"LastExpired":null},"NewPart":{"Id":6,"Reference":"FS12848AD","Stock":1650,"CDP":1.24914646,"LastExpired":"2021-03-11T00:00:00"},"Transformation":{"Id":188,"Possible":true,"Cost":1090.0,"WillBeTransformed":true,"TransformationDate":"2021-03-13T08:48:00","Responsible":"Miguel","EngineeringChangeId":8}}},]
PAGE/AJAX OUTPUT outputs are created by console.log() and Console.WriteLine() displayed above.
ECRNumber gets named to ecrNumber...

Need to shift the child nodes in json to parent node

I have the following JSON -
[{
"ctin":"guju3j3jgjh3b",
"inv":[
{
"inum":"OS1920/16060",
"idt":"01-08-2019",
"val":17000.00,
"pos":"20",
"rchrg":"N"
}, {
"inum":"OS1920/16066",
"idt":"02-08-2019",
"val":17602.00,
"pos":"29",
"rchrg":"N"
}
]
},{
"ctin":"guj324djgjh3b",
"inv":[
{
"inum":"OS1920/16064",
"idt":"03-08-2019",
"val":19125.00,
"pos":"26",
"rchrg":"N"
}
]
}
.
.
.
]
I need to combine the child and the parent node.
So that the result will come as following -
[{
"ctin":"guju3j3jgjh3b",
"inum":"OS1920/16060",
"idt":"01-08-2019",
"val":17000.00,
"pos":"20",
"rchrg":"N"
}, {
"ctin":"guju3j3jgjh3b",
"inum":"OS1920/16066",
"idt":"02-08-2019",
"val":17602.00,
"pos":"29",
"rchrg":"N"
}, {
"ctin":"guj324djgjh3b",
"inum":"OS1920/16064",
"idt":"03-08-2019",
"val":19124,
"pos":"26",
"rchrg":"N"
},
.
.
.
]
Tried searching SO, but no luck.
Also, tried removing the "INV" node, but no luck. It just goes [object object] in Angular due to the looping of nodes inside one another.
It can be done using map function and concat:
const data = [{
"ctin":"guju3j3jgjh3b",
"inv":[
{
"inum":"OS1920/16060",
"idt":"01-08-2019",
"val":17000.00,
"pos":"20",
"rchrg":"N"
}, {
"inum":"OS1920/16066",
"idt":"02-08-2019",
"val":17602.00,
"pos":"29",
"rchrg":"N"
}
]
},{
"ctin":"guj324djgjh3b",
"inv":[
{
"inum":"OS1920/16064",
"idt":"03-08-2019",
"val":19125.00,
"pos":"26",
"rchrg":"N"
}
]
}
];
and code is:
let notFlattened = data.map(({ctin, inv}) => {
inv = inv.map(r=> {
r.ctin = ctin;
return r;
});
return inv;
})
let merged = [].concat.apply([], notFlattened);
console.log(merged);
I can only assume that the JSON is an array. You can use a combination of the .map, .reduce and .concat methods of Array to get what you want:
const result = data
.map((item) => item.inv.map((inv) => ({ ctin: item.ctin, ...inv })))
.reduce((a, b) => a.concat(b), []);
Try This,
for (var j = 0; j < this.datasource.length; j++) {
for (var i = 0; i < this.datasource1[j].inv.length; i++) {
this.datasource[j].inv[i].ctin = this.datasource[j]["ctin"];
}
/* delete this.datasource[j]['ctin'];
this.result.push(this.datasource[j].inv); */
}

How do I change an UI/Image when there's 2 gameobjects with the same name?

I'm developing an application for the hololens that generates multiple canvases with a panel with UI/Image elements. I have 1 JSON string:
{
"PC_Station":[
{
"PLC_0":{
"DB1":{
"test123":0
},
"STOP":false,
"Frap":false,
"START":false,
"Start_1":false,
"Stop_1":false,
"Led1":true,
"Led2":false,
"Led3":true,
"Counter":4002,
"Sliderval":0
}
},
{
"PLC_1":{
"DB1":{
"test123":55
},
"STOP":false,
"START":false,
"Start_1":false,
"Stop_1":false,
"Led1":true,
"Led2":false,
"Led3":true,
"Counter":4002,
"Sliderval":0
}
}
]
}
This JSON string has 2 JSON objects inside a JSON array called PLC_1 and PLC_0. PLC_1 has the same variables as PLC_0.
I've made the following function that appends the JSON and changes the color of the UI/Image objects:
IEnumerator updateTags()
{
string json = "{\"PC_Station\": [{\"PLC_1\": {\"DB1\": {\"test123\": 30}, \"STOP\": false, \"START\": true, \"Start_1\": false, \"Stop_1\": true, \"Led1\": false, \"Led2\": false, \"Led3\": false, \"Counter\": 3880, \"Sliderval\": 60}}]}";
string json1 = "{\"PC_Station\": [{\"PLC_0\": {\"DB1\": {\"test123\": 0}, \"STOP\": false,\"Frap\": false, \"START\": false, \"Start_1\": false, \"Stop_1\": false, \"Led1\": true, \"Led2\": false, \"Led3\": true, \"Counter\": 4002, \"Sliderval\": 0}},{\"PLC_1\": {\"DB1\": {\"test123\": 55}, \"STOP\": false, \"START\": false, \"Start_1\": false, \"Stop_1\": false, \"Led1\": true, \"Led2\": false, \"Led3\": true, \"Counter\": 4002, \"Sliderval\": 0}}]}";
var data = JToken.Parse(json1);
while (true)
{
foreach (var value in data)
{
foreach(JArray arr in value)
{
for (int i = 0; i < arr.Count; i++)
{
foreach (var item in arr[i])
{
var itemproperties = item.Parent;
foreach (JToken token in itemproperties)
{
var prop = token as JProperty;
var plc = (JObject)prop.Value;
foreach (KeyValuePair<string, JToken> val in plc)
{
if(val.Value is JObject)
{
JObject nestedobj = (JObject)val.Value;
foreach (JProperty nestedvariables in nestedobj.Properties())
{
string varkey = nestedvariables.Name;
string varvalue = nestedvariables.Value.ToString();
GameObject test = GameObject.Find(varkey+"value");
test.GetComponent<Text>().text = varvalue;
}
}
else
{
for(int v = 0; v < abc.Count; v++)
{
Debug.Log(v);
foreach(KeyValuePair<string, string> variab in abc[v])
{
string varkey = val.Key;
string varvalue = val.Value.ToString();
GameObject test = GameObject.Find(varkey);
if(varvalue == "True")
{
test.GetComponent<Image>().color = Color.green;
}
if(varvalue == "False")
{
test.GetComponent<Image>().color = Color.red;
}
if(varvalue != "True" && varvalue != "False")
{
GameObject text = GameObject.Find(varkey + "value");
text.GetComponent<Text>().text = varvalue;
}
}
}
}
}
}
}
}
}
}
yield return new WaitForSeconds(0.5f);
}
}
When I run the programme, it looks like this:
As you can see, the function properly adds color to the UI/Images.
Now, for my question:
How can I make it so that the UI/Images on both canvases get filled with color despite having the same name?
There are no obvious solutions as GameObject referenes do not serialize easily, you couls reference objects by their position in the current branch of the tree (transform.GetSiblingIndex()) but that will not work if you move stuff around.
You could also just rename your objects.
Managed to fix it by using transform.find. I used it to find items in the hierarchy.
The code now functions like I want it to.
First I make a new gameobject:
public GameObject upd4;
Then I use it in my code as follows:
upd4 = transform.Find("Canvas" + i + "/Panel/" + plcvvobj.Key + "/" + plcvvobj.Key + "value").gameObject;
BTW, my hierarchy is as follows:

JQGgrid- How to generate a pdf / excel file from the grid data

I have the following JQGrid table, which is being generated from JSON data. I want to be able to generate/export or create a pdf file based on the table data state that is view able. I am using JSON , Jqgrid and Javascript
How do I generate a pdf file from the data ?
Here My FIDDLE
JS CODE
$(document).ready(function() {
var jsonData = {
"Name": "Julie Brown",
"Account": "C0010",
"LoanApproved": "12/5/2015",
"LastActivity": "4/1/2016",
"PledgedPortfolio": "4012214.00875",
"MaxApprovedLoanAmt": "2050877.824375",
"LoanBalance": "1849000",
"AvailableCredit": "201877.824375",
"Aging": "3",
"Brokerage": "My Broker",
"Contact": "Robert L. Johnson",
"ContactPhone": "(212) 902-3614",
"RiskCategory": "Yellow",
"rows": [{
"ClientID": "C0010",
"Symbol": "WEC",
"Description": "Western Electric Co",
"ShareQuantity": "20638",
"SharePrice": "21.12",
"TotalValue": "435874.56",
"LTVCategory": "Equities",
"LTVRatio": "50%",
"MaxLoanAmt": "217937.28"
}, {
"ClientID": "C0010",
"Symbol": "BBB",
"Description": "Bins Breakers and Boxes",
"ShareQuantity": "9623",
"SharePrice": "74.29125",
"TotalValue": "714904.69875",
"LTVCategory": "Equities",
"LTVRatio": "50%",
"MaxLoanAmt": "357452.349375"
}, {
"ClientID": "C0010",
"Symbol": "GPSC",
"Description": "Great Plains Small Cap Stock",
"ShareQuantity": "49612",
"SharePrice": "14.24",
"TotalValue": "706474.88",
"LTVCategory": "Mutual Funds - Small Cap",
"LTVRatio": "40%",
"MaxLoanAmt": "282589.952"
}]
},
mmddyyyy = "";
/*********************************************************************/
$("#output").jqGrid({
url: "/echo/json/",
mtype: "POST",
datatype: "json",
postData: {
json: JSON.stringify(jsonData)
},
colModel: [
/** { name: 'ClientID', label:'ClientID',width: 80, key: true },****/
{
name: 'Symbol',
width: 65
}, {
name: 'Description',
width: 165
}, {
name: 'ShareQuantity',
align: 'right',
width: 85,
classes: "hidden-xs", labelClasses: "hidden-xs",
formatter: 'currency',
formatoptions: {
prefix: " ",
suffix: " "
}
}, {
name: 'SharePrice',
label: 'Share Price',
align: 'right',
width: 100,
classes: "hidden-xs", labelClasses: "hidden-xs",
template: "number",
formatoptions: {
prefix: " $",
decimalPlaces: 4
}
},
/*{ label: 'Value1',
name: 'Value1',
width: 80,
sorttype: 'number',
formatter: 'number',
align: 'right'
}, */
{
name: 'TotalValue',
label: 'Total Value',
width: 160,
sorttype: 'number',
align: "right",
search: false,
formatter: 'currency',
formatoptions: {
prefix: " $",
suffix: " "
}
}, {
name: 'LTVRatio',
label: 'LTV Ratio',
width: 70,
sorttype: 'number',
align: "right",
formatter: 'percentage',
formatoptions: {
prefix: " ",
suffix: " "
}
}, {
name: 'LTVCategory',
label: 'LTV Category',
classes: "hidden-xs", labelClasses: "hidden-xs",
width: 120,
width: 165
},
{
name: 'MaxLoanAmt',
label: 'MaxLoanAmount',
width: 165,
sorttype: 'number',
align: "right",
search: false,
formatter: 'currency',
formatoptions: {
prefix: " $",
suffix: " "
}
}
],
additionalProperties: ["Symbol", "Description"],
subGrid: true,
subGridRowExpanded: function (subgridDivId, rowid) {
var item = $(this).jqGrid("getLocalRow", rowid);
$("#" + $.jgrid.jqID(subgridDivId)).html("Symbol: <em>" + item.Symbol +
"</em><br/>Description: <em>" + item.Description + "</em>");
},
beforeProcessing: function (data) {
var symbolsMap = {}, symbolsValues = ":All", rows = data.rows, i, symbol;
for (i = 0; i < rows.length; i++) {
symbol = rows[i].Symbol;
if (!symbolsMap.hasOwnProperty(symbol)) {
symbolsMap[symbol] = 1;
symbolsValues += ";" + symbol + ":" + symbol;
}
}
$(this).jqGrid("setColProp", 'Symbol', {
stype: "select",
searchoptions: {
value: symbolsValues
}
}).jqGrid('destroyFilterToolbar')
.jqGrid('filterToolbar', {
stringResult: true,
searchOnEnter: false,
defaultSearch : "cn"
});
},
/*beforeProcessing: function (data) {
var item, i, n = data.length;
for (i = 0; i < n; i++) {
item = data[i];
item.Quantity = parseFloat($.trim(item.Quantity).replace(",", ""));
item.LTVRatio = parseFloat($.trim(item.LTVRatio *10000).replace(",", ""));
item.Value = parseFloat($.trim(item.Value).replace(",", ""));
item.Num1 = parseInt($.trim(item.Num1).replace(",", ""), 10);
item.Num2 = parseInt($.trim(item.Num2).replace(",", ""), 10);
}
}, */
iconSet: "fontAwesome",
loadonce: true,
rownumbers: true,
cmTemplate: {
autoResizable: true,
editable: true
},
autoResizing: {
compact: true
},
autowidth: true,
height: 'auto',
forceClientSorting: true,
sortname: "Symbol",
footerrow: true,
caption: "<b>Collateral Value</b> <span class='pull-right' style='margin-right:20px;'>Valuation as of: " + mmddyyyy + "</span>",
loadComplete: function() {
var $self = $(this),
sum = $self.jqGrid("getCol", "Price", false, "sum"),
sum1 = $self.jqGrid("getCol", "MaxLoanAmt", false, "sum");
//ltvratio = $self.jqGrid("getCol","LTVRatio:addas", "Aved Loan Amount");
$self.jqGrid("footerData", "set", {
LTVCategory: "Max Approved Loan Amount:",
Price: sum,
MaxLoanAmt: sum1
});
}
});
$("#output").jqGrid('filterToolbar', {stringResult: true, searchOnEnter: false, defaultSearch : "cn"});
$(window).on("resize", function () {
var newWidth = $("#output").closest(".ui-jqgrid").parent().width();
$("#output").jqGrid("setGridWidth", newWidth, true);
}).triggerHandle("resize");
});
There is no build in method to export jqgrid data to pdf. You have to use third party tools( I personally like iTextSharp which can be downloaded from Here . You have to create action method for printing the grid data in your controller.
Here is also another one example one guy made.
Here is also another example in trirand. If you see the source code they are using iTextHsarp.
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using JQGridMVCExamples.Models;
using Trirand.Web.Mvc;
using System.IO;
//
// For PDF export we are using the free open-source iTextSharp library.
//
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.Data;
namespace JQGridMVCExamples.Controllers.Grid
{
public partial class GridController : Controller
{
// This is the default action for the View. Use it to setup your grid Model.
public ActionResult ExportPDF()
{
// Get the model (setup) of the grid defined in the /Models folder.
var gridModel = new OrdersJqGridModel();
var ordersGrid = gridModel.OrdersGrid;
// Setting the DataUrl to an action (method) in the controller is required.
// This action will return the data needed by the grid
ordersGrid.DataUrl = Url.Action("PDFGrid_DataRequested");
// customize the default Orders grid model with custom settings
// NOTE: you need to call this method in the action that fetches the data as well,
// so that the models match
SetPDFExportGrid(ordersGrid);
// Pass the custmomized grid model to the View
return View(gridModel);
}
// This method is called when the grid requests data
public JsonResult PDFGrid_DataRequested()
{
// Get both the grid Model and the data Model
// The data model in our case is an autogenerated linq2sql database based on Northwind.
var gridModel = new OrdersJqGridModel();
var northWindModel = new NorthwindDataContext();
// customize the default Orders grid model with our custom settings
SetPDFExportGrid(gridModel.OrdersGrid);
// Save the current grid state in Session
// We will later need it for PDF Export
JQGridState gridState = gridModel.OrdersGrid.GetState();
Session["gridState"] = gridState;
// return the result of the DataBind method, passing the datasource as a parameter
// jqGrid for ASP.NET MVC automatically takes care of paging, sorting, filtering/searching, etc
return gridModel.OrdersGrid.DataBind(northWindModel.Orders);
}
public JsonResult PDFExport_AutoCompleteShipName(string term)
{
var northWindModel = new NorthwindDataContext();
JQAutoComplete autoComplete = new JQAutoComplete();
autoComplete.DataField = "ShipName";
autoComplete.AutoCompleteMode = AutoCompleteMode.BeginsWith;
autoComplete.DataSource = from o in northWindModel.Orders
select o;
return autoComplete.DataBind();
}
private void SetPDFExportGrid(JQGrid ordersGrid)
{
// show the search toolbar
ordersGrid.ToolBarSettings.ShowSearchToolBar = true;
ordersGrid.ToolBarSettings.ShowSearchButton = true;
var orderDateColumn = ordersGrid.Columns.Find(c => c.DataField == "OrderDate");
orderDateColumn.DataFormatString = "{0:yyyy/MM/dd}";
orderDateColumn.SearchType = SearchType.DatePicker;
orderDateColumn.DataType = typeof(DateTime);
orderDateColumn.SearchControlID = "DatePicker";
orderDateColumn.SearchToolBarOperation = SearchOperation.IsEqualTo;
var shipNameColumn = ordersGrid.Columns.Find(c => c.DataField == "ShipName");
shipNameColumn.SearchType = SearchType.AutoComplete;
shipNameColumn.DataType = typeof(string);
shipNameColumn.SearchControlID = "AutoComplete";
shipNameColumn.SearchToolBarOperation = SearchOperation.Contains;
var orderIDColumns = ordersGrid.Columns.Find(c => c.DataField == "OrderID");
orderIDColumns.Searchable = true;
orderIDColumns.DataType = typeof(int);
orderIDColumns.SearchToolBarOperation = SearchOperation.IsEqualTo;
SetPDFCustomerIDSearchDropDown(ordersGrid);
SetPDFFreightSearchDropDown(ordersGrid);
}
private void SetPDFCustomerIDSearchDropDown(JQGrid ordersGrid)
{
// setup the grid search criteria for the columns
JQGridColumn customersColumn = ordersGrid.Columns.Find(c => c.DataField == "CustomerID");
customersColumn.Searchable = true;
// DataType must be set in order to use searching
customersColumn.DataType = typeof(string);
customersColumn.SearchToolBarOperation = SearchOperation.IsEqualTo;
customersColumn.SearchType = SearchType.DropDown;
// Populate the search dropdown only on initial request, in order to optimize performance
if (ordersGrid.AjaxCallBackMode == AjaxCallBackMode.RequestData)
{
var northWindModel = new NorthwindDataContext();
var searchList = from customers in northWindModel.Customers
select new SelectListItem
{
Text = customers.CustomerID,
Value = customers.CustomerID
};
customersColumn.SearchList = searchList.ToList<SelectListItem>();
customersColumn.SearchList.Insert(0, new SelectListItem { Text = "All", Value = "" });
}
}
private void SetPDFFreightSearchDropDown(JQGrid ordersGrid)
{
// setup the grid search criteria for the columns
JQGridColumn freightColumn = ordersGrid.Columns.Find(c => c.DataField == "Freight");
freightColumn.Searchable = true;
// DataType must be set in order to use searching
freightColumn.DataType = typeof(decimal);
freightColumn.SearchToolBarOperation = SearchOperation.IsGreaterOrEqualTo;
freightColumn.SearchType = SearchType.DropDown;
// Populate the search dropdown only on initial request, in order to optimize performance
if (ordersGrid.AjaxCallBackMode == AjaxCallBackMode.RequestData)
{
List<SelectListItem> searchList = new List<SelectListItem>();
searchList.Add(new SelectListItem { Text = "> 10", Value = "10" });
searchList.Add(new SelectListItem { Text = "> 30", Value = "30" });
searchList.Add(new SelectListItem { Text = "> 50", Value = "50" });
searchList.Add(new SelectListItem { Text = "> 100", Value = "100" });
freightColumn.SearchList = searchList.ToList<SelectListItem>();
freightColumn.SearchList.Insert(0, new SelectListItem { Text = "All", Value = "" });
}
}
public ActionResult ExportToPDF(string exportType)
{
var gridModel = new OrdersJqGridModel();
var northWindModel = new NorthwindDataContext();
var grid = gridModel.OrdersGrid;
// Get the last grid state the we saved before in Session in the DataRequested action
JQGridState gridState = Session["GridState"] as JQGridState;
// Need to set grid options again
SetExportGrid(grid);
if (String.IsNullOrEmpty(exportType))
exportType = "1";
DataTable exportData;
switch (exportType)
{
case "1":
grid.ExportSettings.ExportDataRange = ExportDataRange.All;
exportData = grid.GetExportData(northWindModel.Orders);
ExportToPDF(exportData);
break;
case "2":
grid.ExportSettings.ExportDataRange = ExportDataRange.Filtered;
exportData = grid.GetExportData(northWindModel.Orders, gridState);
ExportToPDF(exportData);
break;
case "3":
grid.ExportSettings.ExportDataRange = ExportDataRange.FilteredAndPaged;
exportData = grid.GetExportData(northWindModel.Orders, gridState);
ExportToPDF(exportData);
break;
}
return View();
}
private void ExportToPDF(DataTable dt)
{
//
// For PDF export we are using the free open-source iTextSharp library.
//
Document pdfDoc = new Document();
MemoryStream pdfStream = new MemoryStream();
PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDoc, pdfStream);
pdfDoc.Open();//Open Document to write
pdfDoc.NewPage();
Font font8 = FontFactory.GetFont("ARIAL", 7);
PdfPTable PdfTable = new PdfPTable(dt.Columns.Count);
PdfPCell PdfPCell = null;
//Add Header of the pdf table
for (int column = 0; column < dt.Columns.Count; column++)
{
PdfPCell = new PdfPCell(new Phrase(new Chunk(dt.Columns[column].Caption, font8)));
PdfTable.AddCell(PdfPCell);
}
//How add the data from datatable to pdf table
for (int rows = 0; rows < dt.Rows.Count; rows++)
{
for (int column = 0; column < dt.Columns.Count; column++)
{
PdfPCell = new PdfPCell(new Phrase(new Chunk(dt.Rows[rows][column].ToString(), font8)));
PdfTable.AddCell(PdfPCell);
}
}
PdfTable.SpacingBefore = 15f; // Give some space after the text or it may overlap the table
pdfDoc.Add(PdfTable); // add pdf table to the document
pdfDoc.Close();
pdfWriter.Close();
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "application/pdf";
Response.AppendHeader("Content-Disposition", "attachment; filename=gridexport.pdf");
Response.BinaryWrite(pdfStream.ToArray());
Response.End();
}
}
}

i want filter for "Unitprice" and "ProductID"

I WANT FILTER FOR "UnitPrice" AND "ProductID"
This is the sample, you want more
using the jsfiddle link
hen the jsfiddle for more detail & work my program in that
//change event
$("#category").keyup(function () {
var selecteditem = $('#category').val();
var kgrid = $("#grid").data("kendoGrid");
selecteditem = selecteditem.toUpperCase();
var selectedArray = selecteditem.split(" ");
if (selecteditem) {
});
var orfilter = { logic: "or", filters: [] };
var andfilter = { logic: "and", filters: [] };
$.each(selectedArray, function (i, v) {
if (v.trim() == "") {
}
else {
$.each(selectedArray, function (i, v1) {
if (v1.trim() == "") {
}
else {
orfilter.filters.push({ field: "ProductName", operator: "contains", value:v1 },
{ field: "QuantityPerUnit", operator: "contains", value:v1});
andfilter.filters.push(orfilter);
orfilter = { logic: "or", filters: [] };
}
});
}
});
kgrid.dataSource.filter(andfilter);
}
else {
kgrid.dataSource.filter({});
}
});
I WANT FILTER FOR "UnitPrice" AND "ProductID"
visit
js fiddle
This is the sample, you want more
using the jsfiddle link
when the jsfiddle for more detail & work my program in that