jQGrid asp.net mvc 3 implementation from scratch - asp.net-mvc-3

I am trying to implement jQGrid in my application with some basic features including filtering and sub grid. I looked numerous articles but many of them seem to be old and outdated. I think i am struggling with the basics of implementing it. I will really appreciate if you can provide basic controller view structure or refer to any sort of tutorial from scratch with asp. net mvc 3.

Here is the code in the View (first mark-up, then JS):
#model SampleApp.SampleModel
#{
ViewBag.Title = "Stackoverflow Title";
Layout = "~/Views/Shared/_defaultLayout.cshtml";
}
<link href="#Url.Content("~/Content/themes/cupertino/jquery-ui-1.8.13.custom.css")" rel="stylesheet" type="text/css" />
<link href="#Url.Content("~/Content/grid/ui.jqgrid.css")" rel="stylesheet" type="text/css" />
<script src="#Url.Content("~/Scripts/ui/jquery-ui-1.8.12.custom.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/grid/grid.locale-en.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/grid/jquery.jqGrid.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/myJSHelper.js")" type="text/javascript"></script>
<script type="text/javascript" id="loadGridResultsScript1">
// This code LOADs the grid by calling the MVC Action to get Data
$(document).ready(function () { helper.loadSearchResults('#Model.JobCode'); });
</script>
<!-- these are the jQuery Grid controls -->
<table id="list" class="scroll" cellpadding="0" cellspacing="0"></table>
<div id="pager" class="scroll" style="text-align:center;"></div>
Here is the JS function from myHelper JS file:
loadSearchResults: function (id) {
$("#list").jqGrid({
url: vpath + '/Sample/GetTargets/' + id,
datatype: 'json', mtype: 'POST', colNames: cols,
colModel: colModel, pager: $('#pager'),
rowNum: 15, rowList: [5, 10, 15, 25, 50, 100], sortname: cols[1],
sortorder: "asc", viewrecords: true,
imgpath: '', caption: ' '
});
$("#list").setGridWidth(1000, true);
$("#list").setGridHeight(350, true);
}
and here is the Action that jQuery calls:
public ActionResult GetTargets(string id, string sidx, string sord, int page, int rows)
{
var repo = IOCContainer.Resolve<DataRepository>();
////////////////////////////////////////////////////////////////////
var job = svc.GetJobByCode(id);
// job is my 'Model', it is a System.Data.DataSet
int pageIndex = Convert.ToInt32(page) - 1;
int pageSize = rows;
int totalRecords = (job.Targets == null) ? 0 : job.Tables[0].Rows.Count;
int totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);
List<DataRow> pageSet = Enumerable.Empty<DataRow>().ToList();
if (totalRecords > 0)
{
// Get rows for current page!!!
if (sord == "asc")
{
if (sidx == " ") sidx = job.Tables[0].Columns[0].ColumnName;
pageSet = job.Tables[0].Rows.Cast<DataRow>()
.OrderBy(q => q[sidx])
.Skip(pageIndex * pageSize)
.Take(pageSize)
.ToList();
}
else
pageSet = job.Targets.Tables[0].Rows.Cast<DataRow>()
.OrderBy(q => q[sidx])
.Reverse()
.Skip(pageIndex * pageSize)
.Take(pageSize)
.ToList();
}
var cols = GetColumnNames(job.Tables[0]);
// Func to get Cells, called later on in code...
Func<DataRow, string[], string[]> getCells = (pkg, columns) =>
{
var cellList = new List<string>();
cellList.Add(pkg[0].ToString());
foreach (var col in columns)
{
if (col.StartsWith("_")) continue;
object cellContent = pkg[col];
string cellText = string.Empty;
if (cellContent is DateTime)
{
cellText = ((DateTime)cellContent).ToString("MM/dd/yyyy");
}
else if (cellContent is decimal || cellContent is double)
{
cellText = string.Format("{0:c}", cellContent);
}
else
{
cellText = String.Format("{0}", cellContent);
}
cellList.Add(cellText);
}
return cellList.ToArray();
};
var jsonData = new
{
total = totalPages,
page,
records = totalRecords,
rows = (
from item in pageSet
select new
{
i = item[0].ToString(),
cell = getCells(item, cols)
}).ToArray()
};
return Json(jsonData);
}
I hope you find this helpful. Let me know if there are any questions

Related

While upgrading from jqrid4.6 to 4.13.5 facing issue in creating a dynamic dropdown with Unique values.dropdown layout get disturbed

Trying to create a demo to show dynamic dropdown for Field-source, client but data is returning null.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js">
var columnNameArrayForColumnFilter=["source","name"];
$(function () {
"use strict";
var mydata = [
{id:"1", invdate:"720:0:0",name:"test", source:"note1", amount:"200.00",tax:"10.00",total:"210.00"},
{id:"2", invdate:"34:09:0",name:"test2", source:"note2", amount:"300.00",tax:"20.00",total:"320.00"},
{id:"3", invdate:"0:0:0",name:"test3", source:"note1", amount:"400.00",tax:"30.00",total:"430.00"},
{id:"4", invdate:"90:08:8",name:"test4", source:"note2", amount:"200.00",tax:"10.00",total:"210.00"},
{id:"5", invdate:"09:34:2",name:"test4", source:"note3", amount:"300.00",tax:"20.00",total:"320.00"},
{id:"6", invdate:"80:12:02",name:"test6", source:"note3", amount:"400.00",tax:"30.00",total:"430.00"},
{id:"7", invdate:"80:12:01",name:"test7", source:"note2", amount:"200.00",tax:"10.00",total:"210.00"},
{id:"8", invdate:"112:23:6",name:"test2", source:"note2", amount:"300.00",tax:"20.00",total:"320.00"},
{id:"9", invdate:"80:12:1 ",name:"test9", source:"note1", amount:"400.00",tax:"30.00",total:"430.00"},
{id:"10",invdate:"112:34:2",name:"test1",source:"note3",amount:"500.00",tax:"30.00",total:"530.00"},
{id:"11",invdate:"114:23:2",name:"test11",source:"note2",amount:"500.00",tax:"30.00",total:"530.00"},
{id:"13",invdate:"80:12:4 ",name:"test11",source:"note2",amount:"500.00",tax:"30.00",total:"530.00"},
{id:"14",invdate:"0:1:0",name:"test11",source:"note12",amount:"500.00",tax:"30.00",total:"530.00"} ,
{id:"15",invdate:"80:12:3",name:"test11",source:"note12",amount:"500.00",tax:"30.00",total:"530.00"}
];
$("#grid").jqGrid({
data: mydata,
colNames:['Inv No','Duration', 'Client', 'Amount','Tax','Total','source'],
colModel:[
{name:'id',index:'id', search:false,width:65, sorttype: 'int'},
{name:'invdate',index:'invdate', width:120, align:'center', sorttype:'datetime', datefmt:'H:i:s',searchoptions: { sopt:['inbetween','eq','lt','le','gt','ge'] }},
{name:'name',index:'name', width:90,search:true,},
{name:'amount',index:'amount', width:70, formatter:'number', align:"right",search:false,},
{name:'tax',index:'tax', width:60, formatter:'number', align:"right",search:false,},
{name:'total',index:'total', width:60, formatter:'number',align:"right",search:false,},
{name:'source',index:'source', width:100, search:true,}
],
pager: true,
autoencode: true,
viewrecords: true,
rowNum: 10,
rowList: [5, 10, 20, "10000:All" ],
caption: "Demonstration custom searching operation (Duration Range)",
customSortOperations: {
inbetween: {
operand: "inbetween",
text: "in between",
filter: function (options) {
}
}
}
}).jqGrid("filterToolbar",
{stringResult: true, searchOnEnter: true, searchOperators : true});
applyColumnFilterOnGrid(columnNameArrayForColumnFilter,'grid');
});
function applyColumnFilterOnGrid(columnNameArrayForColumnFilterInGrid)
{
for(var i=0;i<columnNameArrayForColumnFilterInGrid.length;i++)
{
setSearchSelect.call("#grid",columnNameArrayForColumnFilterInGrid[i]);
}
}
// this function return unique value for column filter on grid
var getUniqueNames = function(columnName) {
var data = $('#grid').jqGrid('getGridParam', 'data');
var uniqueTexts = [], text, textsMap = {}, i;
for (i = 0; i < data.length; i++) {
text = data[i][columnName];
if (text !== undefined && textsMap[text] === undefined) {
// to test whether the texts is unique we place it in the map.
textsMap[text] = true;
uniqueTexts.push(text);
}
}
return uniqueTexts;
}
// this method add All value in column filter values and return value map
var buildSearchSelect = function(uniqueNames) {
var values=":All";
$.each (uniqueNames, function() {
values += "," + this + ":" + this;
});
return values;
};
// this function is create drop down for column filter functionlity on grid and set values
var setSearchSelect = function(columnName) {
$("#grid").jqGrid("setColProp", columnName,
{
stype:"select",
searchoptions: {
value:buildSearchSelect(getUniqueNames.call("#grid",columnName)),
sopt:["eq"]
}
}
);
};
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/themes/redmond/jquery-ui.css">
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
<!--<link rel="stylesheet" href="../jqGrid/css/ui.jqgrid.css">-->
<link rel="stylesheet" href="http://www.ok-soft-gmbh.com/jqGrid/OK/ui.jqgrid.css">
<html lang="en">
<head>
</head>
<body>
<div id="outerDiv" style="margin:5px;">
<table id="grid"></table>
</div>
</body>
</html>
When I try to upgrade from 4.6 to 4.13.5 .. my existing dynamic dropdown unique values get disturbed.
The current code has some simple errors like the usage of $("grid") instead of $("#grid") inside of getUniqueNames and setSearchSelect and creating filterToolbar before filling searchoptions.value with the data: you call applyColumnFilterOnGrid after filterToolbar instead of before filterToolbar.
The next problem exists in the buildSearchSelect, which I published originally in the old answer. You changed the line
values += ";" + this + ":" + this;
to
values += "," + this + ":" + this;
which is wrong. One should use ; instead of , as the separator (see the documentation of jqGrid 4.6). If you replace "," to ";" then the problem will be solved. In general you can use , instead of ; as the separator in the value, but you should inform jqGrid about that by usage delimiter: "," option:
var setSearchSelect = function(columnName) {
$("#grid").jqGrid("setColProp", columnName,
{
stype:"select",
searchoptions: {
delimiter: ",",
value:buildSearchSelect(getUniqueNames.call("#grid",columnName)),
sopt:["eq"]
}
}
);
};

Call Ajax.ActionLink using Razor syntax on value changed event

I have a View in which i have criteria a Supplier TextBox a LastMonth dropdown and a Months Textbox.
#using JouleBrokerDB.ViewModels;
#model AssignPayReportToDepositViewModel
#{
ViewBag.Title = "View";
}
<link href="#Url.Content("~/Content/kendo/kendo.common-bootstrap.min.css")" rel="stylesheet" />
<link href="#Url.Content("~/Content/kendo/kendo.bootstrap.min.css")" rel="stylesheet" />
<link href="#Url.Content("~/Content/kendo/kendo.dataviz.min.css")" rel="stylesheet" />
<link href="#Url.Content("~/Content/kendo/kendo.dataviz.bootstrap.min.css")" rel="stylesheet" />
<style>
.treediv {
display: inline-block;
vertical-align: top;
width: 440px;
/*height:400px;*/
min-height: 400px;
text-align: left;
margin: 0 2em;
border-radius: 25px;
border: 2px solid #8AC007;
padding: 15px;
overflow: auto;
}
</style>
<div class="row">
<div class="col-md-9 col-md-offset-1">
#using (Html.BeginForm("Show", "AssignPayReportToDeposit", FormMethod.Post, new { id = "AssignToPayReportForm", #class = "form-horizontal" }))
{
<fieldset>
<!-- Form Name -->
<legend>Assign Pay Report to Deposit</legend>
<div class="form-group">
<!-- Supplier -->
<div class="col-sm-4">
#Html.Label("", "Supplier:", new { #class = "control-label", #for = "textinput" })
<div id="suppliers">
#Html.DropDownListFor(x => x.SuppliersList, new SelectList(Model.SuppliersList, "SupplierID", "Name"), new { id = "ddSupplier", #class = "form-control" })
</div>
</div>
<!-- Last Month -->
<div class="col-sm-4">
#Html.Label("", "Last Month:", new { #class = "control-label", #for = "textinput" })
#Html.DropDownListFor(x => x.LastMonthsList, new SelectList(Model.LastMonthsList), new { #id = "ddLastMonth", #class = "form-control" })
</div>
<!-- Months-->
<div class="col-sm-4">
#Html.Label("", "Months:", new { #class = "control-label", #for = "textinput" })
#Html.TextBox("txtMonths", null, new { type = "number", step = 1, min = 1, max = 12, #class = "form-control", required = "required" })
</div>
</div>
</fieldset>
<div class="treediv">
#Html.Label("", "UnAssigned PayReport:", new { #class = "control-label", #for = "textinput" })
<div id="TreeView_UPR" style="padding:5px"></div>
</div>
<div class="treediv">
#Html.Label("", "Deposits:", new { #class = "control-label", #for = "textinput" })
<h4></h4>
<div id="TreeView_AD" style="padding:5px"></div>
</div>
}
</div>
</div>
<script src="#Url.Content("~/Scripts/kendo/kendo.all.min.js")"></script>
<script src="#Url.Content("~/Scripts/Views/AssignPayReportToDeposit/Show.js")"></script>
Here on this text box i have attached changed event though jQuery. The requirement is that whenever the criteria changes the treeview div will be filled with data will be refreshed.
AssignPayReportsToDeposit.AttachEvents = function () {
$("#ddSupplier").change(AssignPayReportsToDeposit.OnSupplierChange);
$("#ddLastMonth").change(AssignPayReportsToDeposit.OnLastMonthChange);
$("#txtMonths").change(AssignPayReportsToDeposit.OnMonthsChange);
}
these changed event handler will handle the refreshing the treeview. The whole thing is handled through ajax calls.
Now i know that using Ajax.ActionLink and UpdateTargetId parameter with Replace option i can return the treeview in partial view so the manual handling can be removed. but that will require me put the anchor button which user have to click. Requirement is that the refresh of treeview should be done on any criteria change.
Is there any way i am able to achieve this using Ajax.ActionLink (or any another razor syntax that will take load off from the manual handling ) ? On change event of the controls i would like to call a controller using ajax.actionlink which will return a partialview and update the div.
Edit: I am handling this through jQuery right now. so i will post the complete code for more understanding.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using JouleBrokerDB;
using JouleBrokerDB.ViewModels;
using JouleBroker.Filters;
namespace JouleBroker.Controllers
{
[RoutePrefix("AssignPayReportToDeposit")]
[Route("{action=Show}")]
public class AssignPayReportToDepositController : Controller
{
// GET: AssignPayReportToDeposit
//[Route("Show",Name = "APTDShow")]
//[ValidateLogin]
public ActionResult Show()
{
List<SupplierViewModel> suppliers = DBCommon.GetAllSuppliers(false);
SuppliersList_LastMonthsList_ViewModel model = new SuppliersList_LastMonthsList_ViewModel()
{
SuppliersList = suppliers,
LastMonthsList = new List<string>()
};
return View(model);
}
[HttpPost]
[Route("GetUnAssignedPayReports")]
public JsonResult GetUnAssignedPayReports(int SupplierID,
string MonthPaid,
int Months)
{
var payreports = AssignPayReportsToDepositData.GetUnAssignedPayReports(SupplierID,
MonthPaid,
Months);
return Json(payreports);
}
[HttpPost]
[Route("GetAssignedPayReports")]
public JsonResult GetAssignedPayReports(int SupplierID,
string MonthPaid,
int Months)
{
var payreports = AssignPayReportsToDepositData.GetAssignedPayReports(SupplierID,
MonthPaid,
Months);
return Json(payreports);
}
[HttpPost]
[Route("AssignDepositIdToPayReport")]
public bool AssignDepositIdToPayReport(int PayReportID, int DepositID)
{
return AssignPayReportsToDepositData.AssignDepositIdToPayReport(PayReportID, DepositID);
}
}
}
JavaScript File (the code is a bit lengthy so you don't need to look at all of them you can see the methods which are calling the action methods. GetUnAssignedPayReports and GetAssignedPayReports which returns the data which is used to fill the tree view.) I just want this portion to moved to partial view and passing model to partial view generate treeview there and replace the div each time on change event with rendering partial view again. Hope i am clear enough. so change the above methods to return partial instead of json result that what i am trying to achive
function AssignPayReportsToDeposit() { }
AssignPayReportsToDeposit.SelectedSupplierID = 0;
AssignPayReportsToDeposit.SelectedLastMonth = null;
AssignPayReportsToDeposit.SelectedMonths = 0;
AssignPayReportsToDeposit.LastMonthsList = null;
AssignPayReportsToDeposit.UnAssignedPayReportsList = null;
AssignPayReportsToDeposit.AssignedPayReportsList = null;
AssignPayReportsToDeposit.LastTextChangedNode = null;
//--------- Document Ready Function -------- //
$(document).ready(function () {
//AttachEvents
AssignPayReportsToDeposit.AttachEvents();
});
AssignPayReportsToDeposit.AttachEvents = function () {
$("#ddSupplier").change(AssignPayReportsToDeposit.OnSupplierChange);
$("#ddLastMonth").change(AssignPayReportsToDeposit.OnLastMonthChange);
$("#txtMonths").change(AssignPayReportsToDeposit.OnMonthsChange);
}
//Handles Supplier ChangeEvents
AssignPayReportsToDeposit.OnSupplierChange = function () {
//Get Changed Supplier ID
AssignPayReportsToDeposit.SelectedSupplierID = $('#ddSupplier').val();
//Get Last Month List
AssignPayReportsToDeposit.LastMonthsList = CommonAction.GetLastPayReportMonthsBySupplierID(AssignPayReportsToDeposit.SelectedSupplierID);
//Fill Last Month List
AssignPayReportsToDeposit.FillLastMonths();
//Refresh TreeView_UPR
AssignPayReportsToDeposit.RefreshTreeViewUPR();
//Refresh TreeView_AD
AssignPayReportsToDeposit.RefreshTreeViewAD();
}
//Handles Last Month Change Event
AssignPayReportsToDeposit.OnLastMonthChange = function () {
AssignPayReportsToDeposit.SelectedLastMonth = $('#ddLastMonth').val();
//Refresh TreeView_UPR
AssignPayReportsToDeposit.RefreshTreeViewUPR();
//Refresh TreeView_AD
AssignPayReportsToDeposit.RefreshTreeViewAD();
}
//Handles Month Change Event
AssignPayReportsToDeposit.OnMonthsChange = function () {
AssignPayReportsToDeposit.SelectedMonths = $('#txtMonths').val();
//Refresh TreeView_UPR
AssignPayReportsToDeposit.RefreshTreeViewUPR();
//Refresh TreeView_AD
AssignPayReportsToDeposit.RefreshTreeViewAD();
}
//Fills Last Month Dropdown with options
AssignPayReportsToDeposit.FillLastMonths = function () {
var ddLastMonth = $("#ddLastMonth");
if (ddLastMonth != undefined) {
ddLastMonth.empty();
if (AssignPayReportsToDeposit.LastMonthsList != undefined) {
$.each(AssignPayReportsToDeposit.LastMonthsList, function () {
Common.AddOptionToSelect(ddLastMonth, this.Text, this.Text);
});
ddLastMonth.val(AssignPayReportsToDeposit.LastMonthsList[0].Text);
AssignPayReportsToDeposit.SelectedLastMonth = ddLastMonth.val();
}
}
}
AssignPayReportsToDeposit.ValidateControls = function () {
var success = true;
if (AssignPayReportsToDeposit.SelectedSupplierID == undefined ||
AssignPayReportsToDeposit.SelectedSupplierID == 0) {
// bootbox.alert('Please select a Supplier');
success = false;
}
else if (AssignPayReportsToDeposit.SelectedLastMonth == undefined ||
AssignPayReportsToDeposit.SelectedLastMonth == '') {
// bootbox.alert('Please select Last Month');
success = false;
}
else if (AssignPayReportsToDeposit.SelectedMonths == undefined ||
AssignPayReportsToDeposit.SelectedMonths == 0) {
// bootbox.alert('Please Enter Months');
success = false;
}
return success;
}
//Assigns DepositIdToPayReport
AssignPayReportsToDeposit.AssignDepositIdToPayReport = function (PayReportID, DepositID) {
var success = false;
if (PayReportID != undefined && DepositID != undefined) {
var jsonData = JSON.stringify({ PayReportID: PayReportID, DepositID: DepositID });
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: 'AssignPayReportToDeposit/AssignDepositIdToPayReport',
data: jsonData,
async: false,
success: function (result) {
success = result;
},
error: Common.AjaxErrorHandler
});
}
return success;
}
//--------- Tree View UPR Functions -------- //
//Gets UnAssigned Pay Reports
AssignPayReportsToDeposit.GetUnAssignedPayReports = function () {
var payReports;
if (AssignPayReportsToDeposit.ValidateControls()) {
var jsonData = JSON.stringify(
{
SupplierID: AssignPayReportsToDeposit.SelectedSupplierID,
MonthPaid: AssignPayReportsToDeposit.SelectedLastMonth,
Months: AssignPayReportsToDeposit.SelectedMonths
});
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "AssignPayReportToDeposit/GetUnAssignedPayReports",
data: jsonData,
async: false,
success: function (data) {
if (data != undefined && data != "")
payReports = data;
},
error: Common.AjaxErrorHandler
});
}
return payReports;
}
AssignPayReportsToDeposit.BindTreeViewUPR = function () {
var treeview = $("#TreeView_UPR");
var inline = new kendo.data.HierarchicalDataSource({
data: AssignPayReportsToDeposit.UnAssignedPayReportsList,
schema: {
model: {
id: "PayReportID"
}
}
});
treeview.kendoTreeView({
dragAndDrop: true,
dataSource: inline,
dataBound: function (e) {
if (!this.dataSource.data().length) {
this.element.append("<p class='no-items'>No items yet.</p>");
} else {
this.element.find(".no-items").remove();
}
},
dataTextField: ["DisplayValue"],
drop: AssignPayReportsToDeposit.OnTreeViewUPRDrop
});
}
AssignPayReportsToDeposit.OnTreeViewUPRDrop = function (e) {
var isTargetTreeViewAD = false;
var sourceDataItem = this.dataItem(e.sourceNode);
var targetDataItem = this.dataItem(e.destinationNode);
if (targetDataItem == undefined) {
targetDataItem = $("#TreeView_AD").data("kendoTreeView").dataItem(e.destinationNode);
isTargetTreeViewAD = true;
}
if (sourceDataItem == undefined ||
targetDataItem == undefined) {
//Source and target both must exists
e.preventDefault();
return;
}
if (sourceDataItem.IsDeposit == true) {
//Deposits cannot be drag and Drop
e.preventDefault();
return;
}
if (isTargetTreeViewAD) {
if (e.dropPosition == "over" &&
sourceDataItem.IsPayReport == true &&
sourceDataItem.IsAssignedPayReport == false &&
targetDataItem.IsDeposit == true) {
//Source must UnAssigned Payreport Target Must be Deposit and Drop position must over
//Implement logic to assign deposit id to the Pay Report
var PayReportID = sourceDataItem.PayReportID;
var DepositID = targetDataItem.DepositID;
if (AssignPayReportsToDeposit.AssignDepositIdToPayReport(PayReportID, DepositID)) {
sourceDataItem.set("DepositID", DepositID);
sourceDataItem.set("IsAssignedPayReport", true);
}
else {
//Didnt update the record don't do the drop
e.preventDefault();
return;
}
}
else {
e.preventDefault();
return;
}
}
else {
if ((e.dropPosition == "before" || e.dropPosition == "after") &&
sourceDataItem.IsPayReport == true &&
targetDataItem.IsPayReport == true &&
targetDataItem.IsAssignedPayReport == false) {
//Only allow sorting in this condition otherwise cancel drop event
//Means only allow sorting of unassigned payreports within the tree
}
else {
e.preventDefault();
return;
}
}
}
AssignPayReportsToDeposit.RefreshTreeViewUPR = function () {
//Destroy and empty tree
var treeview = $("#TreeView_UPR").data("kendoTreeView");
if (treeview != undefined) { treeview.destroy(); }
treeview = $("#TreeView_UPR");
treeview.empty();
AssignPayReportsToDeposit.UnAssignedPayReportsList = AssignPayReportsToDeposit.GetUnAssignedPayReports();
AssignPayReportsToDeposit.BindTreeViewUPR();
}
//--------- TreeView_AD Functions -------- //
//Gets Assigned Pay Reports
AssignPayReportsToDeposit.GetAssignedPayReports = function () {
var payReports;
if (AssignPayReportsToDeposit.ValidateControls()) {
var jsonData = JSON.stringify(
{
SupplierID: AssignPayReportsToDeposit.SelectedSupplierID,
MonthPaid: AssignPayReportsToDeposit.SelectedLastMonth,
Months: AssignPayReportsToDeposit.SelectedMonths
});
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "AssignPayReportToDeposit/GetAssignedPayReports",
data: jsonData,
async: false,
success: function (data) {
if (data != undefined && data != "")
payReports = data;
},
error: Common.AjaxErrorHandler
});
}
return payReports;
}
AssignPayReportsToDeposit.BindTreeViewAD = function () {
var treeview = $("#TreeView_AD");
var inline = new kendo.data.HierarchicalDataSource({
data: AssignPayReportsToDeposit.AssignedPayReportsList,
schema: {
model: {
id: "DepositID",
hasChildren: "HasAnyAssignedPayReports",
children: "AssignedPayReports"
}
}
});
treeview.kendoTreeView({
dragAndDrop: true,
dataSource: inline,
dataBound: function (e) {
if (!this.dataSource.data().length) {
this.element.append("<p class='no-items'>No items yet.</p>");
} else {
this.element.find(".no-items").remove();
}
},
dataTextField: ["DisplayValue", "DisplayValue"],
drop: AssignPayReportsToDeposit.OnTreeViewADDrop,
select: AssignPayReportsToDeposit.OnTreeViewADSelect
});
}
AssignPayReportsToDeposit.OnTreeViewADSelect = function (e) {
var dataItem = this.dataItem(e.node);
var treeview = this;
if (AssignPayReportsToDeposit.LastTextChangedNode != undefined) {
//Restore last node's Text
var previousDataItem = this.dataItem(AssignPayReportsToDeposit.LastTextChangedNode);
if (previousDataItem != undefined) {
var date = AssignPayReportsToDeposit.FormatDepositMonthToDisplay(previousDataItem.DepositDate);
var displaytext = "[" + date + "]" + "-[" + previousDataItem.BankName + "]-" + "[" + previousDataItem.Amount + "]";
this.text(AssignPayReportsToDeposit.LastTextChangedNode, displaytext);
}
AssignPayReportsToDeposit.LastTextChangedNode = undefined;
}
if (dataItem.IsDeposit) {
if (dataItem.hasChildren > 0) {
dataItem.set("expanded", true);
//Append sum to selected node's diplay value
var childs = dataItem.children.data();
var sum = 0;
$.each(childs, function () { sum += this.Amount });
var date = AssignPayReportsToDeposit.FormatDepositMonthToDisplay(dataItem.DepositDate);
var displaytext = "[" + date + "]" + "-[" + dataItem.BankName + "]-" + "[" + dataItem.Amount + "(" + sum + ")" + "]";
this.text(e.node, displaytext)
AssignPayReportsToDeposit.LastTextChangedNode = e.node;
}
}
}
AssignPayReportsToDeposit.FormatDepositMonthToDisplay = function (jsondate) {
var depositedate = "";
if (jsondate != undefined && jsondate != "") {
var date = Common.ParseDate(jsondate);
var month = ("0" + (date.getMonth() + 1)).slice(-2);
depositedate = date.getFullYear() + "-" + (month);
}
return depositedate;
}
AssignPayReportsToDeposit.OnTreeViewADDrop = function (e) {
var isTargetTreeViewURP = false;
var DroptoNoItemZone = false;
var sourceDataItem = this.dataItem(e.sourceNode);
var targetDataItem = this.dataItem(e.destinationNode);
var treeview_UPR = $("#TreeView_UPR").data("kendoTreeView");
if (targetDataItem == undefined) {
targetDataItem = treeview_UPR.dataItem(e.destinationNode);
if (treeview_UPR.element.find(".no-items").length > 0) DroptoNoItemZone = true;
isTargetTreeViewURP = true;
}
if ((sourceDataItem == undefined ||
targetDataItem == undefined) && DroptoNoItemZone == false) {
e.preventDefault();
return;
}
if (sourceDataItem.IsDeposit == true) {
//Deposits can not be moved within the tree view
e.preventDefault();
return;
}
if (isTargetTreeViewURP) {
if (((e.dropPosition == "before" || e.dropPosition == "after") &&
sourceDataItem.IsPayReport == true &&
sourceDataItem.IsAssignedPayReport == true &&
targetDataItem.IsPayReport == true) || (e.dropPosition == "over" && DroptoNoItemZone)) {
//Implement logic to unassing deposit id to PayReport
var PayReportID = sourceDataItem.PayReportID;
var DepositID = 0;
if (AssignPayReportsToDeposit.AssignDepositIdToPayReport(PayReportID, DepositID)) {
sourceDataItem.set("DepositID", DepositID);
sourceDataItem.set("IsAssignedPayReport", false);
}
else {
//Didnt update the record don't do the drop
e.preventDefault();
return;
}
}
else {
e.preventDefault();
return;
}
}
else {
if (e.dropPosition == "over" &&
sourceDataItem.IsPayReport == true &&
targetDataItem.IsDeposit == true) {
//Implement Logic to change deposit ID for assigned payreport
var PayReportID = sourceDataItem.PayReportID;
var DepositID = targetDataItem.DepositID;
if (AssignPayReportsToDeposit.AssignDepositIdToPayReport(PayReportID, DepositID)) {
sourceDataItem.set("DepositID", DepositID);
sourceDataItem.set("IsAssignedPayReport", true);
}
else {
//Didnt update the record don't do the drop
e.preventDefault();
return;
}
}
else {
e.preventDefault();
return;
}
}
}
AssignPayReportsToDeposit.RefreshTreeViewAD = function () {
//Destroy and empty tree
var treeview = $("#TreeView_AD").data("kendoTreeView");
if (treeview != undefined) { treeview.destroy(); }
treeview = $("#TreeView_AD");
treeview.empty();
AssignPayReportsToDeposit.LastTextChangedNode = undefined;
AssignPayReportsToDeposit.AssignedPayReportsList = AssignPayReportsToDeposit.GetAssignedPayReports();
AssignPayReportsToDeposit.BindTreeViewAD();
}
Unfortunately not out the box.
The Ajax extension methods are really just HTML helpers that work with other jQuery libraries. The helpers create the relavant HTML markup (such as adding custom addtributes data-*="") and the client scripts use this to determine their behaviour.
You could create your own MVC HTML helper and script library to handle change events for you however I would recommend looking at a front end framework such as Angular instead. This library would handle all the events declaratively so you don't need to waste time writing event handlers.

How to display a List of objects in C# to javascript using Google JS API in MVC3?

I have a .Net MVC3 website where I want to draw Pie Charts, but the Google Charts API or maybe JSON doesn't work right in my code and I don't know why.
I tried to refer from this sets of codes: MVC4 with Google JS API
This is my ChartController Code:
public ActionResult Sales()
{
return Json(CreateList(), JsonRequestBehavior.AllowGet);
}
public class ItemForChart
{
public String Name { get; set; }
public Int32 Qty { get; set; }
}
public IEnumerable<ItemForChart> CreateList()
{
List<ItemForChart> list = new List<ItemForChart>();
ItemForChart itm1 = new ItemForChart() { Name = "A", Qty = 1 };
ItemForChart itm2 = new ItemForChart() { Name = "B", Qty = 2 };
ItemForChart itm3 = new ItemForChart() { Name = "C", Qty = 3 };
ItemForChart itm4 = new ItemForChart() { Name = "D", Qty = 4 };
list.Add(itm1); list.Add(itm2); list.Add(itm3); list.Add(itm4);
return list;
}
This is my View Code for the Sale ActionResult
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" >
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawChart);
function drawChart() {
$.get('/Chart/Sales', {},
function (data) {
var tdata = new google.visualization.DataTable();
tdata.addColumn('string', 'Name');
tdata.addColumn('number', 'Qty');
for (var i = 0; i < data.length; i++) {
tdata.addRow([data[i].Name, data[i].Qty);
}
var options = {
title: "Sample Charts"
};
var chart1 = new google.visualization.AreaChart(document.getElementById('chart_div1'));
var chart2 = new google.visualization.LineChart(document.getElementById('chart_div2'));
var chart3 = new google.visualization.PieChart(document.getElementById('chart_div3'));
var chart4 = new google.visualization.ColumnChart(document.getElementById('chart_div4'));
chart1.draw(tdata, options);
chart2.draw(tdata, options);
chart3.draw(tdata, options);
chart4.draw(tdata, options);
});
}
</script>
<div id="chart_div1" style="width: 900px; height: 500px;">
</div>
<div id="chart_div2" style="width: 900px; height: 500px;">
</div>
<div id="chart_div3" style="width: 900px; height: 500px;">
</div>
<div id="chart_div4" style="width: 900px; height: 500px;">
</div>
And when I run the program, it shows this,
[{"Name":"A","Qty":1},{"Name":"B","Qty":2},{"Name":"C","Qty":3},{"Name":"D","Qty":4}]
^it doesn't show any charts but only that.
or if there are other Charts API that I can use that is also easy to learn, I am open for suggestion.
It seems like you are browsing to the JSON controller endpoint localhost/MyApp/Chart/Sales (which is consumed by the Ajax callback in google.setOnLoadCallback to feed data to the chart) - it looks like the JsonRresult is working fine. In order to view the Graph, you'll need to browse to the "Sale ActionResult" route (something like localhost/MyApp/SomeController/Sale)
You also have a typo:
for (var i = 0; i < data.length; i++) {
tdata.addRow([data[i].Name, data[i].Qty]);
// ^ closing array brace
}
Fixed jsFiddle
Not directly related, but note that you can use Object initializer syntax on the server C# to simplify matters:
public IEnumerable<ItemForChart> CreateList()
{
return new List<ItemForChart>
{
new ItemForChart() { Name = "A", Qty = 1 },
new ItemForChart() { Name = "B", Qty = 2 },
new ItemForChart() { Name = "C", Qty = 3 },
new ItemForChart() { Name = "D", Qty = 4 }
}
}

changing rally basic dropdown menus after display

I have a rally.sdk.ui.basic.Dropdown menu in a Rally App that I would like to change based on user input. So I will call display() on the dropdown menu, and then later I want to change the contents of that menu.
Has anybody done this? When I try, it crashes. I've also tried calling destroy() on the dropdown menu and then calling display() on a new menu that I allocate, but that crashes as well with an obscure dojo error.
Any suggestions on how to change dropdown menus on the fly?
I've included a very stripped down example below of trying to destroy and then re-display the menu:
<html>
<head>
<title>Incoming Defects by Severity</title>
<meta http-equiv="X-UA-Compatible" content="IE=7" >
<meta name="Name" content="Defects by Severity" />
<script type="text/javascript" src="https://rally1.rallydev.com/apps/1.29/sdk.js"></script>
<script type="text/javascript">
function DefectChart() {
this.display = function() {
var defectVersionDropdown;
var count = 1;
function makeDefectChart(results){
initDefectVersionDropdown();
};
function renderPage() {
var queryConfig = [];
var startDate = '2011-06-06';
var endDate = '2012-02-02';
var queryArray = ['CreatedDate >= "' + startDate + '"', 'CreatedDate <= "' + endDate + '"'];
var versionFilter = defectVersionDropdown ? defectVersionDropdown.getDisplayedValue() : 'ALL';
if (versionFilter != 'ALL') {
queryArray.push('FoundInBuild contains "' + versionFilter + '"');
}
// console.log(queryArray);
queryConfig.push({
type : 'Defects',
key : 'defects',
query: rally.sdk.util.Query.and(queryArray),
fetch: 'Severity,State,LastUpdateDate,CreationDate,OpenedDate,AcceptedDate,LastUpdateDate,ClosedDate,Environment,FoundInBuild'
});
rallyDataSource.findAll(queryConfig, makeDefectChart);
}
function defectVersionChange(sender, eventArgs) {
var version = eventArgs.value;
renderPage();
}
function initDefectVersionDropdown() {
if (defectVersionDropdown != null) {
defectVersionDropdown.destroy();
defectVersionDropdown = null;
}
if (defectVersionDropdown == null) {
console.log('initDefectVersionDropdown');
count++;
var menuItems = [{label: "ALL", value: "ALL"}];
for (var i=0; i < count; i++) {
menuItems.push({label: count, value: count});
}
var config = {
label: "Found In Version:",
items: menuItems
};
defectVersionDropdown = new rally.sdk.ui.basic.Dropdown(config);
defectVersionDropdown.addEventListener("onChange", defectVersionChange);
defectVersionDropdown.display("defectVersionDiv");
}
}
var workspaceOid = '__WORKSPACE_OID__'; if (workspaceOid.toString().match(/__/)) { workspaceOid = XXX; }
var projectOid = '__PROJECT_OID__'; if (projectOid.toString().match(/__/)) { projectOid = XXX; }
rallyDataSource = new rally.sdk.data.RallyDataSource( workspaceOid,
projectOid,
'__PROJECT_SCOPING_UP__',
'__PROJECT_SCOPING_DOWN__');
initDefectVersionDropdown();
renderPage();
}
}
function getDataAndShow() {
var defectChart = new DefectChart();
defectChart.display();
}
function loadRally() {
rally.addOnLoad(getDataAndShow);
}
loadRally();
</script>
</head>
<body>
<div id="defectVersionDiv"></div>
</body>
</html>
Destroying the old one creating and displaying a new one is the correct way to do this. This is a common pattern when developing apps using the App SDK. If you provide a code snipped along with the dojo error you are getting the community can probably be of better assistance.

ASP.NET MVC 3 WebGrid Sort Order Image

I am working with a WebGrid, and I would like to have an image or character like "^" "v" in the header showing the column with the sort order.
How can I do this?
This is the code of one of my Webgrids:
<div id="contenedor-gridACTIVIDAD">
#{
WebGrid gridACTIVIDAD = new WebGrid(Model.actividadDiaria, ajaxUpdateContainerId: "contenedor-gridACTIVIDAD", rowsPerPage: 20);
}
#gridACTIVIDAD.GetHtml(
fillEmptyRows: true,
alternatingRowStyle: "fila-alternativa",
headerStyle: "encabezado-grid",
footerStyle: "pie-grid",
mode: WebGridPagerModes.All,
firstText: "<<",
previousText: "<",
nextText: ">",
lastText: ">>",
columns: new[] {
gridACTIVIDAD.Column("contrato", header: "Contrato"),
gridACTIVIDAD.Column("Observacion", header: "Observación"),
gridACTIVIDAD.Column("DESCR", header: "Tarea"),
gridACTIVIDAD.Column("FECHA", header: "Fecha",
format: (item) =>
{
return item.fecha.ToString("dd/MM/yyyy");
}
),
gridACTIVIDAD.Column("",
header: "ESTADO",
format: (item) =>
{
if (item.estado == "VC")
{
return Html.Image("/Imagenes/vc.gif","Validado correcto", new { #border = "0"});
}
else if (item.estado == "VI")
{
return Html.Image("/Imagenes/vi.gif", "Validado incorrecto", new { #border = "0" });
}
else if (item.estado == "NV")
{
return Html.Image("/Imagenes/vp.gif", "No validado", new { #border = "0" });
}
else
{
return Html.Image("/Imagenes/nv.png", "Pendiente validar", new { #border = "0" });
}
}
),
gridACTIVIDAD.Column("JDP", header: "JDP")
}
)
</div>
I've solved this issue on server side using HTMLAgilityPack.
This is the code for the view:
WebGrid webGrid = new WebGrid(Model.myModel, defaultSort: "title", rowsPerPage: 20);
IHtmlString webGridHtml = webGrid.GetHtml(
columns: webGrid.Columns(
webGrid.Column("id", "ID"),
webGrid.Column("title", "Title")
)
);
#Helper.GetExtendedWebGrid(webGrid, webGridHtml);
And this is the code for the Helper class:
public static IHtmlString GetExtendedWebGrid(WebGrid webGrid, IHtmlString webGridHtml)
{
HtmlString result;
string webGridHtmlString = webGridHtml.ToString();
HtmlDocument htmlDocument = new HtmlDocument();
htmlDocument.LoadHtml(webGridHtmlString);
HtmlNode htmlNodeAnchor = htmlDocument.DocumentNode.SelectSingleNode("//a[contains(#href,'" + webGrid.SortColumn + "')]");
if (htmlNodeAnchor != null)
{
string imgSortDirection;
if (webGrid.SortDirection == SortDirection.Ascending)
imgSortDirection = "asc";
else
imgSortDirection = "desc";
HtmlNode htmlNodeIcon = HtmlNode.CreateNode("<img src=\"/images/" + imgSortDirection + ".png\" width=\"10\" height=\"10\" />");
htmlNodeAnchor.ParentNode.AppendChild(htmlNodeIcon);
webGridHtmlString = htmlDocument.DocumentNode.OuterHtml;
}
result = new HtmlString(webGridHtmlString);
return result;
}
I just did a google search on "webgrid sort indicator" and came back with a result from http://prokofyev.blogspot.com/2011/01/sort-indicator-in-systemwebhelperswebgr.html
Basically, the person uses jQuery to add in the sort direction image.
<script type="text/javascript">
$('thead > tr > th > a[href*="sort=#grid.SortColumn"]').parent()
.append('#(grid.SortDirection == SortDirection.Ascending ? "U" : "D")');
</script>
(As an added bonus, I just tested it myself, so you can copy and paste this code (the link one is a picture instead of a code sample :( ...) just replace the U and D with whatever you want to display instead.
Hope that helps.
This page has a very simple example of how to implement the sorting arrow or images, when using the WebGrid with AJAX.
http://www.mikesdotnetting.com/Article/203/Enhancing-The-WebGrid-With-Sort-Arrows

Resources