How to load JSON data into SlickGrid with Razor MVC-4 - c#

I am new to jquery, slick grid and razor. I have gone through SlickGrid examples and am able to load static data into a SlickGrid. Now I am trying to load JSON data from MSSQL into my SlickGrid. I have seen a few examples online, but I believe I am missing something not mentioned in those examples.
Here is what I have code.
SlickGridProducts.js
var grid;
var columns = [
{ id: "ProductID", name: "ProductID", field: "ProductID", width: 50 },
{ id: "ItemDesc", name: "ItemDesc", field: "ItemDesc", width: 200 },
{ id: "DivName", name: "DivName", field: "DivName", width: 50 },
{ id: "DeptDesc", name: "DeptDesc", field: "DeptDesc", width: 75 },
{ id: "ClassDesc", name: "ClassDesc", field: "ClassDesc", width: 100 },
{ id: "SubClassDesc", name: "SubClassDesc", field: "SubClassDesc", width: 100 }
];
var options = {
editable: true,
enableAddRow: true,
enableCellNavigation: true,
asyncEditorLoading: false,
autoEdit: false
};
$(function () {
var slickdata = [];
$.getJSON("/Products/GetSlickGridData", function (items) {
for (var i = 0; i < items.length; i++) {
slickdata[i] = {
ProductID: items[i].ProductID,
ItemDesc: items[i].ItemDesc,
DivName: items[i].DivName,
DeptDesc: items[i].DeptDesc,
ClassDesc: items[i].ClassDesc,
SubClassDesc: items[i].SubClassDesc
};
}
});
grid = new Slick.Grid("#myGrid", slickdata, columns, options);
grid.setSelectionModel(new Slick.RowSelectionModel());
grid.setActiveCell(0, 0);
})
Products/Index.cshtml
#model IEnumerable<JQGrid.Models.Product>
#{
ViewBag.Title = "Index";
}
<link href="#Url.Content("~/Content/slick.grid.css")" rel="stylesheet" type="text/css" />
<script src="#Url.Content("~/Scripts/jquery-1.8.2.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.event.drag.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/SlickGrid/slick.core.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/SlickGrid/slick.grid.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/SlickGridProducts.js")" type="text/javascript"></script>
<h2>Index</h2>
<div id="myGrid" style="width:800px;height:300px;"></div>
ProductsController.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using JQGrid.Models;
namespace JQGrid.Controllers
{
public class ProductsController : Controller
{
private ProductPickerEntities db = new ProductPickerEntities();
//
// GET: /Products/
public ActionResult Index()
{
return View(db.Products.ToList());
}
...
public JsonResult GetSlickGridData()
{
var slickGridData = db.Products.ToList();
return Json(slickGridData, JsonRequestBehavior.AllowGet);
}
}
}
If I add a breakpoint in JsonResult GetSlickGridData() and watch slickGridData, I see that it is populated with all the items I want in my slickgrid.
With this all I get is a blank white box for my slick grid. I figure the problem is in my js where I am filling slickdata, but not sure what to fix.
**** Revision *****
I found one of my issues, but the slickgrid is still blank. My issue was the json result being returned was too large. So I modified my ProductsController.cs code for right now to say
public JsonResult GetSlickGridData()
{
var slickGridData = db.Products.ToList();
var jsonResult = Json(slickGridData, JsonRequestBehavior.AllowGet);
jsonResult.MaxJsonLength = int.MaxValue;
return jsonResult;
}
This resolves the maxlength error although I had thought this was resolved in MVC-4.

Did you check the browser console for errors?

You're initializing grid.setSelectionModel(new Slick.RowSelectionModel());, but have not included a reference to it.
It is slick.rowselectionmodel.js and is typically under the Plugins folder.

Related

Pie chart using chart.js and asp.net web Service (asmx)

I have a static pie-chart created using chartJS and now I want to provide the data and labels from an asp.net webservice(asmx) to show the actual data that comes from the database but I don't know how to do that.
This is the Static Chart Code
<!doctype html>
<html>
<head>
<title>Pie Chart</title>
<script src="../../dist/Chart.min.js"></script>
<script src="../utils.js"></script>
</head>
<body>
<div id="canvas-holder" style="width:40%">
<canvas id="chart-area"></canvas>
</div>
<script>
var config = {
type: 'pie',
data: {
datasets: [{
data: [420,576,812],
backgroundColor: [
"#3e95cd", "#8e5ea2", "#3cba9f"
],
label: 'Labels'
}],
labels: [
'iPhone',
'Windows Phone',
'Samsung'
]
},
options: {
responsive: true
}
};
window.onload = function () {
var ctx = document.getElementById('chart-area').getContext('2d');
window.myPie = new Chart(ctx, config);
};
</script>
</body>
</html>
The Data I want to Show
Phone as Chart Label and Amount as Chart-Data
-------------------------
-Phone - Amount-
-------------------------
-iPhone - 323 -
-Windows-Phone - 210 -
-Samsung - 860 -
-------------------------
The Web Service that fetch the data
[WebMethod]
public void GetTotalPhoneSales()
{
string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
List<TotalSales> totalSales = new List<TotalSales>();
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("spGetTotalPhoneSales", con)
{
CommandType = CommandType.StoredProcedure
};
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
TotalSales PhoneSale = new TotalSales
{
Amount = Convert.ToInt32(rdr["Amount"]),
Phone = rdr["Phone"].ToString()
};
totalSales.Add(PhoneSale);
}
}
JavaScriptSerializer js = new JavaScriptSerializer();
Context.Response.Write(js.Serialize(totalSales));
}
Expected output
You may call the web service method from Jquery Ajax function and return the values.
What you have to change is
1) Change the return type of your web method to string[][](Array of string Arrays:because we need to return two arrays)
2) Call this web method with the help of Jquery ajax function and in the success function assign the data and label options with respective arrays received from the jquery ajax call.
documentation of Jquery ajax function
Finally I solved it like this
<script>
//make an ajax call to the webservice
//then use `chartlabel` as label and `chartData` as Data
var chartLabel= [];
var chartData= [];
$.ajax({
url: 'TestService.asmx/GetTotalPhoneSales',
method: 'post',
dataType: 'json',
success: function (data) {
$(data).each(function (index, item) {
chartLabel.push(item.Phone);
chartData.push(item.Amount);
});
},
error: function (err) {
alert(err);
}
});
var config = {
type: 'pie',
data: {
datasets: [{
data: chartData,
backgroundColor: [
"#3e95cd", "#8e5ea2", "#3cba9f"
],
label: 'Labels'
}],
labels: chartLabel
},
options: {
responsive: true
}
};
window.onload = function () {
var ctx = document.getElementById('chart-area').getContext('2d');
window.myPie = new Chart(ctx, config);
};
</script>
Note: Its better to assign the backgroundColor programmatically, so that when new items are added to the database then those items will not show up with same color on the chart by default.
thanks for the hint #Gagan Deep

How to format google chart x axis in DateTime format from C#

I'm developing a web site in MVC 5 and I'm using google chart to display some chart for my data. I'm using the line chart for a data which have a value and a date. Something like the follow:
class ChartData
{
public double Value { get; set; }
public DateTime Date { get; set; }
};
In my controller I have a request handler to generate the data for the chart:
public JsonResult GenerateChartData(int id)
{
List<ChartData> list = new List<ChartData>();
// some code to populate the list
return Json(list, JsonRequestBehavior.AllowGet);
}
Everything works fine except that the X axis which should show the date time sequence is formatted in the wrong way. The looks like absolute time not in readable date format.
see the chart output
thanks for any answer
google charts will accept dates in a couple ways,
which depend on how the data table, used to draw the chart, is loaded...
1)
if you're using one of the following methods to load the data table...
addRow(), addRows(), arrayToDataTable()
the date will need to be a javascript date object,
created using the new keyword,
any valid constructor will work
new Date();
new Date(value);
new Date(dateString);
new Date(year, month[, date[, hours[, minutes[, seconds[, milliseconds]]]]]);
2)
if using json to load the data table directly...
var data = new google.visualization.DataTable(jsonData);
the following string format can be used...
which needs to be a string value (wrapped in quotes), without the new keyword...
"Date(Year, Month, Day, Hours, Minutes, Seconds, Milliseconds)"
where Month is zero-based
"Date(2017, 4, 16)" // <-- 5/16/2017
This is the way to load the data inside a java script. But in my case the data are generate in json format by a request to the controller. I post the code of my page
#model BDF.RemoteData.Data.TagData
#{
ViewBag.Title = "Chart";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>[[[Grafico]]]</h2>
<input type="hidden" id="idInput" data-value="#ViewBag.id" />
<input type="hidden" id="idSystem" data-value="#ViewBag.system" />
<input type="hidden" id="idStart" data-value="#ViewBag.start" />
<input type="hidden" id="idEnd" data-value="#ViewBag.end" />
<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()
{
var id = $("#idInput").data("value");
var system = $("#idSystem").data("value");
var start = $("#idStart").data("value");
var end = $("#idEnd").data("value");
$.ajax(
{
type: 'POST',
dataType: 'json',
contentType: 'application/json',
url: '#Url.Action("GenerateChartData")',
data:
{
id: id,
system: system,
start: start,
end: end
},
type: "GET",
error: function (xhr, status, error)
{
var err = eval("(" + xhr.responseText + ")");
toastr.error(err.message);
},
beforeSend: function ()
{
},
success: function (data)
{
HistDashboardChart(data);
return false;
},
error: function (xhr, status, error)
{
var err = eval("(" + xhr.responseText + ")");
toastr.error(err.message);
},
complete: function ()
{
}
});
return false;
}
//This function is used to bind the user data to chart
function HistDashboardChart(data)
{
$("#Data_Chart").show();
var dataArray = [
['Date', 'Value']
];
$.each(data, function (i, item)
{
dataArray.push([item.Date, item.Value]);
});
var data = google.visualization.arrayToDataTable(dataArray);
var options = {
legend:
{
position: 'bottom',
textStyle:
{
color: '#f5f5f5'
}
},
colors: ['#34A853', 'ff6600', '#FBBC05'],
backgroundColor: '#454545',
hAxis:
{
title: 'Time',
titleTextStyle:
{
italic: false,
color: '#00BBF1',
fontSize: '20'
},
textStyle:
{
color: '#f5f5f5'
}
},
vAxis:
{
baselineColor: '#f5f5f5',
title: 'Values',
titleTextStyle:
{
color: '#00BBF1',
italic: false,
fontSize: '20'
},
textStyle:
{
color: '#f5f5f5'
},
viewWindow:
{
min: 0,
format: 'long'
}
},
curveType: 'function',
};
var chart = new google.visualization.LineChart(document.getElementById('Data_Chart'));
chart.draw(data, options);
return false;
};
</script>
<div id="Data_Chart" style="width: 100%; height: 500px"> </div>
As you can see the job id done by the request url: '#Url.Action("GenerateChartData")'
Then the returned data are pushed into an array the the code
var dataArray = [
['Date', 'Value']
];
$.each(data, function (i, item)
{
dataArray.push([item.Date, item.Value]);
});
In this case I'm assuming that item.Date is already in a datetime format but maybe I have to format it in a special way.
The output of the console.log(item.Date) is the following:
/Date(1494937128000)/
/Date(1494937133000)/
/Date(1494937138000)/
/Date(1494937143000)/
/Date(1494937148000)/
/Date(1494937153000)/
/Date(1494937158000)/
/Date(1494937163000)/
Which looks strange I think, doesn't it?
Ok I got it. Reading this article made everything clear
How to parse JSON to receive a Date object in JavaScript?
I modified the java script code inside my page in the following way:
var dataArray = [
['Date', 'Value']
];
$.each(jsondata, function (i, item) {
var d = new Date(parseInt(item.Instant.substr(6)));
dataArray.push([d, item.Value]);
});
Now it works perfectly

How to Implement Autocomplete Textbox in MVC

I am facing a problem in autocompleting the textbox vith hardcoded data, my json "Search" method does not fire i have been search a lot of code implement it into my project but did not get any success yet. i dont know where is the problem. kindly help me thankx in advance
Model:
public class Locations
{
public int Id { get; set; }
public string Name { get; set; }
}
Controller:
public JsonResult Search(string query)
{
List<Locations> locations = new List<Locations>()
{
new Locations() {Id = 1, Name = "London"},
new Locations() {Id = 2, Name = "Walles"},
new Locations() {Id = 3, Name = "Birmingham"},
new Locations() {Id = 4, Name = "Edinburgh"},
new Locations() {Id = 5, Name = "Glasgow"},
new Locations() {Id = 6, Name = "Liverpool"},
new Locations() {Id = 7, Name = "Bristol"},
new Locations() {Id = 8, Name = "Manchester"},
new Locations() {Id = 9, Name = "NewCastle"},
new Locations() {Id = 10, Name = "Leeds"},
new Locations() {Id = 11, Name = "Sheffield"},
new Locations() {Id = 12, Name = "Nottingham"},
new Locations() {Id = 13, Name = "Cardif"},
new Locations() {Id = 14, Name = "Cambridge"},
new Locations() {Id = 15, Name = "Bradford"},
new Locations() {Id = 16, Name = "Kingston Upon Hall"},
new Locations() {Id = 17, Name = "Norwich"},
new Locations() {Id = 18, Name = "Conventory"}
};
List<string> Loc;
Loc = locations.Where(x => x.Name.StartsWith(query.ToLower())).Select(x => x.Name).ToList();
return Json(Loc, JsonRequestBehavior.AllowGet);
}
View:
#model IEnumerable<SearchBox.Models.Locations>
#using SearchBox.Models
#{
ViewBag.Title = "Index";
}
<link href="~/Content/Autocomplete/jquery-ui.css" rel="stylesheet" />
<script src="~/Content/Autocomplete/jquery-ui.js"></script>
<link href="~/Content/Autocomplete/jquery-ui.theme.css" rel="stylesheet" />
<script type="text/javascript">
$("#tags").autocomplete({
source: '#Url.Action("Search")'
});
</script>
<input type="text" id="tags" />
You need to make ajax request instead of passing just url in data source.
<link href="~/Content/jquery-ui.css" rel="stylesheet" />
<script src="~/Content/jquery-1.12.4.js"></script>
<script src="~/Content/jquery-ui.js"></script>
<input type="text" id="tags" />
<script type="text/javascript">
$("#tags").autocomplete({
source: function (request, response) {
$.ajax({
url: '#Url.Action("Search")',
dataType: "jsonp",
data: {
term: request.term
},
success: function (data) {
response($.map(data, function (item) {
return {
label: item.Name,
value: item.Id
};
}));
}
});
},
minLength: 2,
select: function (event, ui) {
}
});
</script>
See how to use autocomplete with ajax request.
I have implemented this in my project. Please check if you can make use of it
<div class="tag_cover" style="margin-top:60px; margin-left:57px">
<input type="text" style="width:300px; display:inline-block; border:transparent" class="tag_input brzero has-icon" id="SkillSet" list="json-datalist" placeholder="Employee name or Skills">
<datalist id="json-datalist"></datalist>
</div>
JQuery:
$(".tag_input").keyup(function (e) {
var type = $("input[name='search']:checked").val();
if (type == "Name") {
var sString = $("#SkillSet").val();
if (sString == null || sString == "") {
e.preventDefault();
}
else {
$.ajax({
url: "#Url.Action("GetEmployeeNameByKeyword","Home")",
type: "POST",
data: { 'SearchedString': sString },
dataType: "json",
success: function (data) {
if (data == null || data == "") {
//alert("no skills found");
}
else {
var dataList = document.getElementById('json-datalist');
$(dataList).empty();
$.each(data, function (key, value) {
$(dataList).append($('<option>').text(value.UserNames.trim()).attr("value", value.UserId));
});
}
},
error: function () {
alert("failure");
}
});
}
}
}
Controller:
public JsonResult GetEmployeeNameByKeyword(string SearchedString)
{
List<UserProfile> EmployeeNames = new List<UserProfile>();
EmployeeNames = _db.UserProfiles.Where(i => i.UserNames.Contains(SearchedString)).ToList();
return Json(EmployeeNames, JsonRequestBehavior.AllowGet);
}
I have been looking everywhere for references on a feature like this, myself.
I don't have enough rep to comment, but Naveen's answer worked for me after I started going one line at a time with console.log("PASS");. If the function is never called on an event like keyup, then it likely means one of the variable names is wrong or there is bad syntax. The reason you could not get any calls to the javascript was because of a missing }); which is an ending statement for JQuery functions. The end of the code for the scripting part should appear like so:
}
}); //END $.ajax
}
}
}); //END keyup function
Using Razor, with T4MVC at an MVC5 project, we'll implement jQuery Autocomplete.
You should have inside your solution, one or more projects, and inside your project, among many other usual MVC5 things, the folders Models, Views and Controllers. And inside of them...
NuGet
Get the dependencies in place (your should know how to get them using Visual Studio):
jQuery: https://www.nuget.org/packages/jQuery/3.6.0
jQuery-UI: https://www.nuget.org/packages/jQuery.UI/
Then put them in the BundleConfig.cs files, at the App_Start folder:
using System.Web.Optimization;
namespace MyProject.Web
{
public class BundleConfig
{
public static void RegisterBundles(BundleCollection bundles)
{
bundles
.Add(new ScriptBundle("~/bundles/jquery")
.Include(
"~/Scripts/jquery-{version}.js",
"~/Scripts/jquery-ui.js",
));
bundles
.Add(new StyleBundle("~/Content/css")
.Include(
"~/Content/jquery-ui.css"
));
}
}
}
This will add the dependencies you´ll need to the view (see View section down below for more instructions).
Model
namespace MyProject.Web.Models.MyModelFolder
{
public class MyModel
{
public string MyValue { get; set; }
public string MyAnotherValue { get; set; }
public string AndAnotherValue { get; set; }
}
}
View
(Using Bootstrap)
#model MyProject.Web.Models.MyModelFolder.MyModel
<div class="ui-widget">
#Html.LabelFor(model => model.MyValue)
#Html.EditorFor(model => model.MyValue, new { htmlAttributes = new { #class = "form-control", id = "myTextbox" } })
#Html.ValidationMessageFor(model => model.MyValue, "", new { #class = "text-danger" })
</div>
We'll be querying the MyValue field.
And add the dependencies from the BundleConfig.cs where you'll need them in your page:
<header>
#Styles.Render("~/Content/css")
</header>
<body>
<p>Your Content</p>
#Scripts.Render("~/bundles/jquery")
</body>
Adding the Autocomplete
There are two ways you can accomplish this, as:
Internal file to the page or,
as an external .js file.
NOTE: Autocomplete must be always below the required jQuery dependencies.
Internal file
In the .cshtml file. Inside your <body> tag, at the bottom of it:
<script>
$("#myTextbox").autocomplete({
source: '#Url.Action(MVC.MyController.MyMethod())'
});
</script>
Or instead in the...(Choose one, not both!)
External file
In the Scripts folder. Remember to add this block at the bottom of your view to call the function from the outside.
#section Scripts {
<script src="~/Scripts/autocomplete.js"></script>
}
And in the Scripts folder in a JS file add:
$(document).ready(function () {
$("#myTextbox").autocomplete({
source: '/MyController/MyMethod',
});
})
You can see there the method you'll be calling from from the controller.
Controller
#region jQuery Method Calls
using MyProject.Web.Models.MyModelFolder;
public virtual JsonResult MyMethod(string term)
{
// _myViewModel is a partial model
List<MyModel> MyAutocompleteList = new List<MyModel>();
/* In this example I´m using AutoMapper, and getting back the List
from the Database (layer, using Entity Framework), using Repository
Pattern (layer) and Unit of Work Pattern. */
// But you can get the List however way you want.
MyAutocompleteList = _theMapper.GetMyModelList(_operationsLayerService.GetMyModelList());
// This LINQ query makes the magic happen
var result = from U in MyAutocompleteList
where U.MyValue.Contains(term)
// It retrieves a composed string, not just a single value.
select new { value = $"{U.MyValue} | {U.MyAnotherValue} {U.AndAnotherValue}" };
// Security vulnerabilities? https://stackoverflow.com/a/21453075/7389293
return Json(result, JsonRequestBehavior.AllowGet);
}
#endregion
That's it.

How to add a style class in jqGrid Td using asp.net c#

I want Conditionaly change style of td in jqGrid, i tried lots of example but not worked, i think i am doing something wrong, please view my code and help me to find out correct code.
My Code is
$(function () {
$("#dataGrid").jqGrid({
url: 'client.aspx/load_Conversation',
datatype: 'json',
mtype: 'POST',
serializeGridData: function (postData) {
return JSON.stringify(postData);
},
ajaxGridOptions: { contentType: "application/json" },
loadonce: false,
reloadGridOptions: { fromServer: true },
colNames: ['Conversation', 'adminStatus'],
colModel: [{ name: 'Conversation', index: 'message', width: 245 }, { name: 'adminStatus', index: 'isAdmin' }, ],
gridComplete: function () {
var ids = jQuery("#dataGrid").jqGrid('getDataIDs');
for (var i = 0; i < ids.length; i++) {
var status = jQuery("#dataGrid").jqGrid("getCell", ids[i], 'adminStatus');
if (status == "False") {
$j('#' + ids[i]).removeClass("ui-widget-content");
$j('#' + ids[i]).addClass("ChangeStyle");
}
}
},
viewrecords: true,
gridview: true,
jsonReader: {
records: function (obj) { return obj.d.length },
root: function (obj) { return obj.d },
repeatitems: false,
caption: 'Live chat with us'
}
});
$("#dataGrid").hideCol("adminStatus");
$("#dataGrid").jqGrid('setGridHeight', 240);
});
My Code behind is
public static List<Dictionary<string, object>> load_Conversation()
{
WebService wb= new WebService();
DataTable dt = wb.Get();
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row;
foreach (DataRow dr in dt.Rows)
{
row = new Dictionary<string, object>();
row.Add("Conversation", dr["messgae"]);
row.Add("adminStatus", dr["isAdmin"]);
rows.Add(row);
}
return rows;
}
If I correcly understand format of data returned from the server you should remove gridComplete, remove index properties from colModel and to use cellattr in adminStatus if you need to change the style of <td> elements in adminStatus:
colModel: [
{ name: 'Conversation', width: 245 },
{ name: 'adminStatus', cellattr: function (rowId, val) {
if (val === "False") {
return " class='ChangeStyle'";
}
}}
]
You can see an example of very close usage of cellattr in the answer.
It could be important how you defines the CSS rule on ChangeStyle class. If you will don't see the expected results you have to include the definition of CSS rule of ChangeStyle class and the version of jqGrid which you use.
Add the following style and scripts
<link type="text/css" href="http://jqueryrock.googlecode.com/svn/trunk/css/jquery-ui-1.9.2.custom.css" rel="stylesheet" />
<link type="text/css" href="http://jqueryrock.googlecode.com/svn/trunk/jqgrid/css/ui.jqgrid.css" rel="stylesheet" />
<script type="text/javascript" src="http://jqueryrock.googlecode.com/svn/trunk/js/jquery-1.8.3.js"></script>
<script type="text/javascript" src="http://jqueryrock.googlecode.com/svn/trunk/js/jquery-ui-1.9.2.custom.js"></script>
<script src="http://jqueryrock.googlecode.com/svn/trunk/jqgrid/js/grid.locale-en.js" type="text/javascript"></script>
<script src="http://jqueryrock.googlecode.com/svn/trunk/jqgrid/js/jquery.jqGrid.min.js" type="text/javascript"></script>
For More style class in jqGrid Td using asp.net c#

JQGrid in MVC Not Loading the Grid

I have an MVC Edit View that contains Contact Information that is of course editable. In that view I want to add a section containing a JQGrid allowing the user to CRUD notes for the Contact but my grid is not loading with data nor is the method on the controller being called. Can anyone give me any insite?
View Code
<div class="panel panel-info">
<div class="panel-heading">
<h3 class="panel-info">
Contact Note</h3>
</div>
<div class="panel-body">
<div class="scrollableContainer" style="margin-top: -10px;">
<table id="JQGrid1"></table>
<div id="JQGrid1_pager"></div>
</div>
</div>
</div>
<script>
$("#JQGrid1").jqGrid({
url: '#Url.Action("GetNotes", "Contact")',
mtype: "GET",
datatype: "json",
page: 1,
jsonReader: { id: document.getElementById('SelectedContact_ContactID').value },
prmNames: { id: document.getElementById('SelectedContact_ContactID').value },
colNames: ["Id", "ContactId", "Note", "Date Created", "Created By"],
colModel: [
{ key: true, width: 50, name: "ID", hidden: false },
{ width: 60, name: "ContactID", hidden: false },
{ width: 460, name: "Note", hidden: false },
{ width: 160, name: "DateCreated",
formatter: "date", formatoptions: { srcformat: "m/d/Y h:i:s A", newformat: "mm-dd-yyyy" }, hidden: false },
{ width: 160, name: "CreatedBy", hidden: false },
],
height: "auto",
caption: "Notes",
rowNum: 5,
pager: "#JQGrid1_pager",
});
</script>
Controller Code
[HttpGet]
public JsonResult GetNotes(int id)
{
var gridModel = new ContactNotesJQGridModel();
var resultset = _contactNoteRepository.GetNotes(id);
return gridModel.ContactNotesGrid.DataBind(resultset.AsQueryable());
}
GridModel Class
public class ContactNotesJQGridModel
{
public JQGrid ContactNotesGrid { get; set; }
public ContactNotesJQGridModel()
{
ContactNotesGrid = new JQGrid
{
Columns = new List<JQGridColumn>()
{
new JQGridColumn {DataField = "ID", PrimaryKey = true},
new JQGridColumn {DataField = "ContactId"},
new JQGridColumn {DataField = "Note"},
new JQGridColumn {DataField = "DateCreated"},
new JQGridColumn {DataField = "CreatedBy"},
}
};
}
Then in the Edit Call for the Contact in the Contact Controller I set model.ContactNotesGrid = new ContactNotesJQGridModel GetNotes(int id) is never executed eventhough it's specified in the jquery.
You should use postData to add custom parameter to the server response:
postData: { id: 11 }
or
postData: {
id: function () {
return document.getElementById('SelectedContact_ContactID').value;
}
}
You need additionally modify the code of the server to use something like
return Json(someObjectWithReturnedData, JsonRequestBehavior.AllowGet);
I recommend you to add loadError callback to the list of jqGrid option (see the answer) and add gridview: true and autoencode: true option to jqGrid.
P.S. About the errors like "unable to get value of the property integer", "unable to get value of the property decimalSeperator". You should verify that you included locale file like i18n/grid.locale-en.js before jquery.jqGrid.min.js (see the documentation).
Try this :
Check 1:
Move your Jquery script inside the document ready event:
$( document ).ready(function() {
console.log( "ready!" );
});
Check 2:
Check weather your server request having any problem or not:
protected void Application_Error(object sender, EventArgs e)
{
Exception exception = Server.GetLastError();
Response.Clear();
}
Add the above code in your Global.asax and make sure there is no exception during the call. (Put Break point and check)
Check 3:
Watch your browser console log (F12). If there is any exception log please provide that.
Check 4:
Make sure if the call is success the expected json format is valid or not. In most of the cases it will be the major cause.
The above's are just my guesses / this is what i do first, if i have a prob. :)

Categories