I am using a flexigrid in ASP.NET, I am having trouble binding the JSON data with the flexigrid I get the JSOn response from the web service but it doesn't bind with the grid and doesn't display the grid, Where am I wrong. I am using a webservice to return the JSON data , Here is the code which I am using.Thanks.
My js function to get data from the webservice and bind the json with flexigrid
$(document).ready(function () {
var obj;
$.ajax({
type: "post",
contentType: "application/json",
url: "FlexService.asmx/GetData",
data: "{}",
dataType: 'json',
success: function (result) {
obj = $.parseJSON(result.d);
//add data
$("#FlexTable").flexAddData(formatEmployeeResults(obj));
}
});
//init flexigrid
$("#FlexTable").flexigrid({
dataType: 'json',
colModel: [{display: 'ID', name: 'id', width: 90, sortable: true, align: 'center'},
{display: 'First Name', name: 'fName', width: 120, sortable: true,align: 'left'},
{display: 'Last Name', name: 'lName', width: 120, sortable: true, align: 'left'},
{display: 'Role', name: 'uRole', width: 120, sortable: true, align: 'left'},
{display: 'Salary', name: 'sal', width: 80, sortable: true, align: 'left'}],
searchitems: [{display: 'ID', name: 'id'},
{display: 'First Name', name: 'fName', isdefault: true}],
sortname: "ID",
sortorder: "asc",
usepager: true,
title: 'Employees',
useRp: true,
rp: 15,
showTableToggleBtn: true,
width: 750,
height: 200
});
function formatEmployeeResults(Employee) {
var rows = Array();
for (i = 0; i < Employee.length; i++) {
var item = Employee[i];
rows.push({ cell: [item.id, item.fName, item.lName, item.uRole, item.sal]
});
}
return {total: Employee.length, page: 1, rows: rows}
}
});
My web service code :
public string GetData()
{
List<Employee> lst = new List<Employee>();
string strConn = ConfigurationManager.ConnectionStrings["FlexDb"].ConnectionString;
OleDbConnection cnx = new OleDbConnection(strConn);
OleDbCommand cmd = new OleDbCommand("Flex",cnx);
cnx.Open();
cmd.CommandType = CommandType.StoredProcedure;
OleDbDataReader dataReader = cmd.ExecuteReader();
while (dataReader.Read())
{
Employee e1 = new Employee();
e1.id = Convert.ToInt32(dataReader["USER_ID"]);
e1.fName = dataReader["FIRST_NAME"].ToString();
e1.lName = dataReader["LAST_NAME"].ToString();
e1.uRole = dataReader["USER_ROLE"].ToString();
e1.sal = dataReader["SALARY"].ToString();
lst.Add(e1);
}
var jss = new JavaScriptSerializer();
return jss.Serialize(lst);
}
I tried your example, and it works perfectly. The only thing is that you might have forgotten to add the CSS file link in your head tag. For example:
<link href="Content/flexigrid/flexigrid.css" rel="stylesheet" />
Related
i have to create a multiseries line chart which is to need view each series with the value of site id and each series with different position .Just now i'am stuck that can only view one series with one query.
And here is the aspx.vb page
Public Class WaterTreament
Public position As Integer
Public value As Double
Public timestamp As String
End Class
<WebMethod()>
Public Shared Function GetWaterTreament() As List(Of WaterTreament)
Using con As New SqlConnection("Data Source=DESKTOP-B8TBSJH1;Initial Catalog=SAY;Integrated Security=SSPI")
Using cmd As New SqlCommand("select position,dtimestamp ,value from telemetry_log_table where siteid ='S1-21' AND dtimestamp BETWEEN '2021-02-02' AND '2021-02-03' and position='62'and value>0 order by dtimestamp asc")
cmd.Connection = con
Dim wtp As New List(Of WaterTreament)()
con.Open()
Using dr As SqlDataReader = cmd.ExecuteReader()
While dr.Read()
wtp.Add(New WaterTreament() With {
.position = Convert.ToInt32(dr("position").ToString()),
.value = Convert.ToDouble(dr("value").ToString()),
.timestamp = dr("dtimestamp").ToString()
})
End While
End Using
con.Close()
Return wtp
End Using
End Using
End Function
Here is the script for highcharts.
$(document).ready(function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "WebForm1.aspx/GetWaterTreament",
data: "{}",
dataType: "json",
success: OnSuccess_,
error: OnErrorCall_
});
function OnSuccess_(response) {
debugger;
var aData = response.d;
var arr = [];
var arr2 = [];
var timestamp = [];
$.map(aData, function (item, index) {
var i = [item.value];
var obj = {};
var obj1 = {};
var obj2 = {};
obj.name = item.position;
obj.y = item.value;
obj.y1 = item.timestamp;
obj2.data = item.timestamp;
arr.push(obj.y);
arr2.push(obj.y1);
timestamp.push(obj2.data);
console.log(obj2);
});
var myJsonString = JSON.stringify(arr);
var jsonArray = JSON.parse(JSON.stringify(arr));
//Second Value
var myJsonString1 = JSON.stringify(arr2);
var jsonArray1 = JSON.parse(JSON.stringify(arr2));
//third Value
var myJsonString2 = JSON.stringify(timestamp);
var jsonArray2 = JSON.parse(JSON.stringify(timestamp));
//alert(jsonArray);
DreawChart(jsonArray, jsonArray1, jsonArray2);
}
function OnErrorCall_(response) {
alert("Whoops something went wrong!");
}
});
function DreawChart(seriesData1, seriesData2, seriesData3) {
Highcharts.chart('container', {
// $('#container').highcharts({
title: {
text: 'SITE ID'
},
yAxis: {
title: {
text: 'Values',
}
},
xAxis: {
categories: seriesData3
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle'
},
plotOptions: {
series: {
label: {
connectorAllowed: false
},
}
},
series: [{
type: 'line',
name: 'PH',
data: seriesData1
},
{
type: 'line',
name: 'CHLORINE',
data: seriesData1
},
],
responsive: {
rules: [{
condition: {
maxWidth: 500
},
chartOptions: {
legend: {
layout: 'horizontal',
align: 'center',
verticalAlign: 'bottom'
}
}
}]
}
});
}`
What is your issue here exactly?
You may want to try official Highcharts .NET wrapper: dotnet.highcharts.com.
Sample chart and source code in C# with multiple series: https://dotnet.highcharts.com/Highcharts/Demo/Gallery?demo=LineBasic&theme=default
I am trying to fill a jqgrid. The grid is rendered but no data is displayed. I know my controller -- as called through a standard ajax function -- is working. It returns the data I'd expect.
How do I verify that jqgrid is returning the same data and what am I doing incorrectly that is not allowing the data to be dispayed?
jqgrid:
<script type="text/javascript">
jQuery(document).ready(function() {
$.ajaxSetup({ cache: false });
var rvtoken = $("input[name='__RequestVerificationToken']").val();
var ModuleId = #Dnn.ModuleContext.ModuleId;
var TabId = #Dnn.ModuleContext.TabId;
$('#grid').jqGrid({
url: '/DesktopModules/MVC/CW.GridTest/Item/getArtists2',
datatype: 'json',
mtype: 'POST',
contentType: 'application/json',
loadBeforeSend: function(jqXHR) {
jqXHR.setRequestHeader('ModuleId', ModuleId);
jqXHR.setRequestHeader( 'TabId', TabId);
jqXHR.setRequestHeader('RequestVerificationToken', rvtoken);
},
colNames: ['ArtistID', 'ArtistName', 'City'],
colModel: [
{ name: 'ArtistID', index: 'ArtistID', width: 80, align: 'left', editable: false },
{ name: 'Name', index: 'ArtistName', width: 120, align: 'left', editable: true },
{ name: 'Location', index: 'City',width: 60,align: 'left',editable: true}
],
loadError: function (jqXHR, textStatus, errorThrown) {
alert('HTTP status code: ' + jqXHR.status + '\n' +
'textStatus: ' + textStatus + '\n' +
'errorThrown: ' + errorThrown);
alert('HTTP message body (jqXHR.responseText): ' + '\n' + jqXHR.responseText);
},
loadOnce: true,
autoencode: true,
height: '100%',
rowNum: 10,
emptyrecords: 'No records',
sortname: 'ArtistID',
sortorder: 'desc',
viewrecords: true,
caption: 'Artists',
width: 300,
gridview: true,
jsonReader:
{
total: 'total',
page: 'page',
records: 'records',
root: 'rows',
repeatitems: false,
id: 'ArtistID'
}
});
jQuery("#grid").jqGrid('navGrid', '#pager', { edit: false, add: false, del: false });
});
</script>
<div>
<table id="grid"></table>
<div id="pager"></div>
</div>
Returned data from standard ajax:
{
"total":100,
"page":99,
"records":6,
"rows":"[
{\"ArtistID\":1,\"ArtistName\":\"Clayton Knight\",\"City\":\"Tigard\"},
{\"ArtistID\":2,\"ArtistName\":\"Corral Creek Bluegrass\",\"City\":\"Sherwood\"},
{\"ArtistID\":3,\"ArtistName\":\"Never Strangers Band\",\"City\":\"Portland\"},
{\"ArtistID\":5,\"ArtistName\":\"The Hillwilliams\",\"City\":\"Tigard\"},
{\"ArtistID\":7,\"ArtistName\":\"Bobo and the Bobbettes\",\"City\":\"Ellensburg\"},
{\"ArtistID\":27,\"ArtistName\":\"Bobo 5\",\"City\":\"Ellensburg\"}
]"
}
It was my controller. Not that it wasn't working but that it wasn't returning what I thought it should be. I was deserializing the data table for the "rows" element, and then deserializing the entire element again. So, the controller wasn't return a json string that jqgrid could actually work with.
It's all working now...
public String getArtists2()
{
using (var ac = new ArtistListingController())
{
ac.Gets();
ac.LoadDatatable();
DataView view = new DataView(ac.Datatable);
DataTable dt = view.ToTable(false, "ArtistID", "ArtistName", "City");
var jsonData = new
{
page=1,
total = 1, // (ac.RecordCount + rows - 1) / rows,
records = ac.RecordCount,
rows = dt //JsonConvert.SerializeObject(dt)
};
return JsonConvert.SerializeObject(jsonData);
}
}
Returning:
{
"page":1,
"total":1,
"records":6,
"rows":[
{
"ArtistID":1,
"ArtistName":"Clayton Knight",
"City":"Tigard"
},
{
"ArtistID":2,
"ArtistName":"Corral Creek Bluegrass",
"City":"Sherwood"
},
{
"ArtistID":3,
"ArtistName":"Never Strangers Band",
"City":"Portland"
},
{
"ArtistID":5,
"ArtistName":"The Hillwilliams",
"City":"Tigard"
},
{
"ArtistID":7,
"ArtistName":"Bobo and the Bobbettes",
"City":"Ellensburg"
},
{
"ArtistID":27,
"ArtistName":"Bobo 5",
"City":"Ellensburg"
}
]
}
I'm using jqgrid for my project.
So far, jqgrid is ok while I'm using with ahsx file
But when I try to use [WebMethod] in aspx file, I get error 500.
Here is my jqgrid setting
$(document).ready(function () {
$("#JQGrid").jqGrid({
url: 'Testing.aspx/LoadMachineCapacity',
mtype: 'POST',
ajaxGridOptions: { contentType: 'application/json; charset=utf-8' },
datatype: "json",
postData: {},
height: 100,
autowidth: true,
loadtext: "Loading...",
colModel: [
{
name: 'MACHINEID',
index: 'MACHINEID',
label: 'Machine ID',
sortable: false,
editable: false
},
{
name: 'ISACTIVE',
index: 'ISACTIVE',
label: 'IS ACTIVE',
sortable: false,
editable: true
}],
loadonce: true,
serializeGridData: function (postData) {
return JSON.stringify(postData);
},
multiselect: false,
caption: 'Machines',
pager: '#JQGridPager',
pgbuttons: true, rowNum: 10, rowList: [10, 20, 30],
rownumbers: true,
viewrecords: true
, cellEdit: true
, afterEditCell: function (rowid, cellname, value, iRow, iCol) {
alert(value);
},
loadError: function (jqXHR, textStatus, errorThrown) {
alert('HTTP status code: ' + jqXHR.status + '\n' +
'textStatus: ' + textStatus + '\n' +
'errorThrown: ' + errorThrown + '\n' +
'errorDesc.: ' + jqXHR.responseText);
}
});
$("#JQGrid").navGrid('#JQGridPager',
{ view: false, edit: false, search: true, add: false, del: false, refresh: true }
);
});
and here is my server-side code
[WebMethod]
public static string LoadMachineCapacity(string pageIndex)
{
string Result = "";
try
{
string strOracleCnnString = ConfigurationManager.ConnectionStrings["PKERP"].ConnectionString;
OracleConnection oracleConn = new OracleConnection(strOracleCnnString);
string strSQL = " SELECT * " +
" FROM T_CT_MCCP " ;
OracleDataAdapter dataAdapter = new OracleDataAdapter(strSQL, oracleConn);
DataTable dataTable = new DataTable();
dataAdapter.Fill(dataTable);
Result = JsonConvert.SerializeObject(dataTable, Formatting.Indented);
}
catch (Exception e)
{
Result = JsonConvert.SerializeObject(e.Message, Formatting.Indented);
}
return Result;
}
Thank in advance.
Thomas
There are a parameter at Webmethod.
However, your jqGrid setting not config at postData.
Change to postData: {pageIndex: "blabla"}.
I am new in asp.net web form and i am unable to hit the url. Jqgrid is showing but the url to get data is not hitting. This is my aspx content named as emplosyee_list.aspx.
<%# Page Title="" Language="C#" MasterPageFile="~/main.Master" AutoEventWireup="true" CodeBehind="employee_list.aspx.cs" Inherits="CollegeManagementSystem.employee_list" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="Content" runat="server">
<div id="page-wrapper">
Back
<div class="container-fluid">
<div class="col-lg-5">
<div>
<span class="headerFont">Employee List</span>
<hr class="lining"/>
</div>
</div>
</div>
</div>
<div >
<table id="grid">
</table>
</div>
<link href="../Content/Site.css" rel="stylesheet" />
<link href="../Content/jquery.jqGrid/ui.jqgrid.css" rel="stylesheet" />
<link href="../Content/StyleSheet1.css" rel="stylesheet" />
<script src="../Scripts/jquery-1.9.1.js"></script>
<script src="../Scripts/jquery-1.9.1.min.js"></script>
<script src="../Scripts/jquery.jqGrid.js"></script>
<script src="../Scripts/jquery.jqGrid.min.js"></script>
<script src="../Scripts/employeeJquery.js"></script>
</asp:Content>
This is my employee_list.aspx.cs
{
public partial class employee_list : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public string GetList()
{
var list = GetDataFromDB();
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Serialize(list);
}
public static List<Dictionary<string, object>> GetDataFromDB()
{
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(#"Data Source=.;Initial Catalog='College Management System';Integrated Security=True"))
{
using (SqlCommand cmd = new SqlCommand("SELECT username, name, DOB, date, gender,address,mobile,phone,email FROM employee_details ORDER BY username", con))
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
JavaScriptSerializer serializer = new 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>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
return rows;
}
}
}
}
}
And this is my Jqgrid code
$("#grid").jqGrid({
url: '/Admin/employee_list.aspx/GetList',
datatype: "json",
colNames: ['User', 'Name', 'DOB', 'Date',
'Gender', 'Address', "Mobile", 'Phone', 'Email', ],
colModel: [
{ name: 'User', index: 'User', width: 50, stype: 'text' },
{ name: 'Name', index: 'Name', width: 150 },
{ name: 'DOB', index: 'DOB', width: 100 },
{ name: 'Date', index: 'Date', width: 80, align: "right" },
{ name: 'Gender', index: 'Gender', width: 80, align: "right" },
{ name: 'Address', index: 'Address', width: 80, align: "right" },
{ name: 'Mobile', index: 'Mobile', width: 150, sortable: false },
{ name: 'Phone', index: 'Phone', width: 100, sortable: false },
{ name: 'Email', index: 'Email', width: 150, sortable: false }
],
pager: { enable: true, limit: 5, sizes: [2, 5, 10, 20] },
rowNum: 10,
rowList: [10, 20, 30],
sortname: 'id',
viewrecords: true,
pager :'#gridpager',
sortorder: "desc",
edit: true,
add: true,
del: true,
search: true,
searchtext: "Search",
addtext: "Add",
edittext: "Edit",
deltext: "Delete",
caption: "List Employee Details"
});
The url is not hiting and there is no error on consoleWhat is the problem
I see the following errors in your code:
you should include jQuery UI CSS on the HTML page. You can use for example <link href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/redmond/jquery-ui.min.css" rel="stylesheet" />
you can't include both minimized and non-minimized versions on the same page. So you should remove, for example, the references to non-minimized files jquery-1.9.1.js and jquery.jqGrid.js.
you should include the reference to i18n/grid.locale-en.js (or other locale file) before jquery.jqGrid.min.js.
You should remove from GetList() the line JavaScriptSerializer serializer = new JavaScriptSerializer(); and the call of serializer.Serialize. Instead of that the WebMethod should return object. The dot net framework will serialize the object to JSON or XML based on the contentType of HTTP request. The code of GetList method could look like
[WebMethod]
public object GetList()
{
return GetDataFromDB();
}
you should include in the option of jqGrid the following:
mtype: 'POST',
ajaxGridOptions: { contentType: "application/json" },
loadonce: true,
jsonReader: {
root: function (obj) {
// after the fix of WebMethod the next line
// can be reduced to
// return obj.d;
return typeof obj.d === "string" ? $.parseJSON(obj.d) : obj.d;
},
repeatitems: false
},
serializeGridData: function(postData) {
return JSON.stringify(postData);
},
height: "auto",
gridview: true
Moreover the value of pager parameter seems be wrong. You don't wrote which version of jqGrid you use and which fork (). I don't know specific options of Guriddo jqGrid JS, but in case of usage free jqGrid or old jqGrid in version <= 4.7, the pager parameter have wrong value.
I recommend you to remove all index properties from colModel.
I have a dropdown select column in jqgrid and I am populating the dropdown dynamically from the controller action. When I edit a row and select a value from the drop down and click Submit, it calls the controller action specified in the editurl but the drop down select column value is "undefined". I am stuck with this issue for a while, please any suggestions are really helpful. Below is my javascript code
jQuery("#list").jqGrid({
url: '/Home/Update/',
datatype: 'json',
mtype: 'POST',
colNames: [‘Name’, ‘Position’],
colModel: [
{name: ' Name', index: ' Name', width: 50, align: 'center', editable: true,
searchoptions: { sopt: ['eq', 'ne', 'cn']} },
{name: ' Position ', index: ' Position ', width: 75, align: 'center', editable: true,
edittype: 'select', formatter:'select',
editoptions: {
dataUrl: '/Home/GetNames/',
style: "width: 120px",
buildSelect: function (data) {
var response = $.parseJSON(data);
var s = '<select>';
for (var i = 0; i < response.rows.length; i++) {
var r = response.rows[i];
s += '<option value="' + r.Id + '">' + r.cell[0] + '</option>';
}
return s + "</select>";
}
},
searchoptions: { sopt: ['eq', 'ne', 'cn']} }],
ondblClickRow: function (row_id) {
jQuery(this).jqGrid('editGridRow', row_id);
},
pager: jQuery('#list'),
height: '100%',
rowNum: 200,
sortname: ‘Name’,
sortorder: "asc",
editurl: '/Home/Create'
});
I solved the issue with dataEvents property as below:
dataEvents: [{
type: 'change',
fn: function (e) {
var i = $(e.target.value);
}
}]
Hope this helps someone.