Here is my jqGrid, that is not displaying any data.
I'm getting the json response for the grid, but it is not displaying.
Here is what i've done so far.
<script type="text/javascript">
$.jgrid.no_legacy_api = true;
function getCompanyData() {
//debugger;
$.ajax({
url: "jqGrid_pureJS.aspx/GetCompanyList",
data: "{}", // "{}" For empty input data use "{}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (result) {
//debugger;
var grdData = $("#jqGrid")[0];
grdData.addJSONData(result.d);
},
error: function (result) {
//debugger;
}
});
}
$(function () {
$("#jqGrid").jqGrid({
datatype: getCompanyData,
colNames: ['Id', 'Name', 'Address', 'City', 'Phone'],
colModel: [
{ name: 'F1', index: 'invid', width: 55 },
{ name: 'F2', index: 'invdate', width: 90,editable:true },
{ name: 'F3', index: 'amount', width: 80,editable:true, align: 'right' },
{ name: 'F4', index: 'tax', width: 80,editable:true, align: 'right' },
{ name: 'F5', index: 'total', width: 80,editable:true, align: 'right' }
],
pager: $("#pager"),
rowNum: 10,
rowList: [10, 20, 30],
viewrecords: true,
caption: 'My first grid',
width:800
}).navGrid('#pager', { edit:true,view: true, del: false });
});
</script>
And here is my webmethod that posts data.
[WebMethod]
[ScriptMethod(ResponseFormat=ResponseFormat.Json,UseHttpGet=false)]
public static string GetCompanyList()
{
var data = GetAllData();
try
{
string response = JsonConvert.SerializeObject(data, Formatting.Indented);
return response;
}
catch (Exception ex)
{
return ex.Message;
}
}
And here is my json responce captured:
{"d":"
[\r\n
{\r\n
\"F1\": 1.0,\r\n
\"F2\": \"Name\",\r\n
\"F3\": \"Address\",\r\n
\"F4\": \"City\",\r\n
\"F5\": \"Phone\"\r\n
},
\r\n
{\r\n
\"F1\": 10.0,\r\n
\"F2\": \"abc\",\r\n
\"F3\": \"def\",\r\n
\"F4\": \"asd\",\r\n
\"F5\": \"998907\"\r\n
}
]
}
I could see similar question jqgrid not showing data, i've checked it and i did not get rid of my problem though
Why is the json data not appended ? How do i do it ?
Edit
as part of the answer, i've removed my javascript to call the jqGrid and replaced the code for it as posted in the answer by oleg.
Also i've made little changes to the code in the server side.
Here is what the server side code is:
[WebMethod]
[ScriptMethod(UseHttpGet = false)]
public static string GetCompanyList()
{
var data = GetAllData();
//string response = JsonConvert.SerializeObject(data, Formatting.Indented);
return data;
}
public static string GetAllData()
{
try
{
//Grab the connection string defined in web.config
var connectionString = ConfigurationManager.ConnectionStrings["Test_3ConnectionString"].ConnectionString;
DataTable dt = null;
//Command Text
string commandText = "SELECT * FROM EmpDetails";
dt = SQLHelper.ExecuteDataTable(connectionString, CommandType.Text, commandText, "EmpDetails");
string result = JsonConvert.SerializeObject(dt);
return result;
}
catch (Exception ex)
{
throw;
}
}
Things going weird hour by hour. When i run my application i've the following grid.
I only have 9 rows in my table and it is displaying viewing 1-10 of 552.
Can someone please help me what is wrong with the serialization
There are may errors in your code. It looks like you used some retro code example which is at least 3 years old.
The main error in the server code is usage of JsonConvert.SerializeObject inside of web method. If you defines ResponseFormat=ResponseFormat.Json then the method should return object of any type and not string. .Net convert the object automatically to JSON. So the type of return value of GetCompanyList() should be the same as the return type of GetAllData(). After the changes the web method should returns the data like
{
"d": [
{
"F1": 1,
"F2": "Name",
"F3": "Address",
"F4": "City",
"F5": "Phone"
},
{
"F1": 10,
"F2": "abc",
"F3": "def",
"F4": "asd",
"F5": "998907"
}
]
}
The second problem that you use datatype defined as function. It's low-level way which you should never use if you can get the data with respect jQuery.ajax with some parameters. jqGrid provide a lot of different customization way to change parameters of jQuery.ajax used by jqGrid internally. Typically it's enough to specify the options like
url: "jqGrid_pureJS.aspx/GetCompanyList",
mtype: 'POST',
datatype: 'json',
ajaxGridOptions: { contentType: 'application/json; charset=utf-8' },
serializeGridData: function (postData) {
return JSON.stringify(postData);
},
jsonReader: {
repeatitems: false,
root: function (obj) { return obj.d; }
},
gridview: true,
height: "auto",
loadonce: true
It's important additionally to remove all index properties from colModel. The usage of index other as name follows to errors if you use loadonce: true option.
If F1 column contains unique values then I recommend you to add key: true property to the definition of the column "F1".
The results of the changes should be like on the demo:
Related
I know I must be doing a basic mistake but I am new to this. I would like to populate a line chart (chart.js) in my View with data from the server. I have confirmed that the data is received in the View but I suspect that it is in a wrong format.
My Controller:
public ActionResult GetLineChartData()
{
var data = new
{
title = "test_data",
data = new[] {
new { value = "V1", key = "11"},
new{ value = "V2", key = "10"}
}
};
return Json(data, JsonRequestBehavior.AllowGet);
}
On my View:
<canvas id="lineChart" width="400" height="400"></canvas>
<button id="lineChartUpdate">Update Chart</button>
<script>
$(document).ready(function () {
$("#lineChartUpdate").click(function () {
$.ajax({
type: "Post",
url: '#Url.Action("GetLineChartData", "Posts")',
data: {},
dataType: "json",
traditional: true,
success: function (data) {
new Chart('lineChart', {
type: 'line',
data: {
labels: data.data.map(a => a[0]),
datasets: [{
label: 'My Dataset',
data: data.data.map(a => a[1]),
fill: false,
borderColor: 'red'
}]
},
options: {
scales: {yAxes: [{ ticks: { beginAtZero: true } }]}
}
});
}
});
});
});
</script>
I am getting this error: "Invalid scale configuration for scale: yAxes"
This is because it is invalid as the errors says, you are using V2 config with V3.
In V3 all scales are there own object in the scales object instead of 2 arrays.
Changing to:
scales: {
y: {
// Scale config
}
}
Will remove the warning and make the config apply correctly
For all changes between V2 and V3 please read the migration guide
I'm trying to use serverfiltering for autocomplete in Kendo UI (ASP.NET 5, MVC6)
Due to fact that Autocomplete isn't available in MVC Wrapper, i had to use the code below:
<script>
var dataSource = new kendo.data.DataSource({
serverFiltering: true,
serverOperation: true,
type: "aspnetmvc-ajax",
transport: {
read: {
url: "#Url.Content("~/api/Get")",
type: "GET"
}
},
schema: {
data: "Data",
total: "Total"
}
})
$("##Model.Name").kendoAutoComplete({
placeholder: "#Model.Watermark",
minLength: 3,
filter: "contains",
dataSource: dataSource
});
</script>
The problem is that querystring send to controller looks like this :
?sort=&group=&filter=
So it doesn't include any filter information
On serverside im trying to map it to DataSourceRequest
Right now im using following workaround to pass additional parameter to do serversidefiltering but still i'd like to use kendo native filtering for this:
<script>
var dataSource = new kendo.data.DataSource({
serverFiltering: true,
serverOperation: true,
type: "aspnetmvc-ajax",
transport: {
read: {
url: "#Url.Content("~/api/Get")",
type: "GET",
data: onAdditionalData
}
},
schema: {
data: "Data",
total: "Total"
}
})
$("##Model.Name").kendoAutoComplete({
placeholder: "#Model.Watermark",
minLength: 3,
filter: "contains",
dataSource: dataSource
});
function onAdditionalData() {
return {
text: $("##Model.Name").val()
};
}
</script>
Controller code:
[Route("api/Get")]
[HttpGet]
public JsonResult Get([DataSourceRequest] DataSourceRequest request, string text = "")
{
var list = (new List<string>() { "value1", "value2", "value3", "test" } ).AsQueryable();
return Json(list.Where(x => x.Contains(text)).ToDataSourceResult(request));
}
i'm trying to build a select element in the form editing jqgrid by calling an ajax webmethod (asp.net).
Everythings work great if I call a method without parameter. It doesn't work if I try to call a webmethod expecting a string parameter:
this is an extract of the code:
ajaxSelectOptions: { type: "POST", contentType: 'application/json; charset=utf-8', },
colNames: ['City', 'State'],
colModel: [
{
name: 'City',
index: 'City',
align: "center",
width: 80,
searchoptions: { sopt: ['eq', 'ne', 'cn']} ,
edittype: 'select',
editable: true,
editrules: { required: true },
editoptions: {
dataUrl: '<%# ResolveUrl("~/Service/Domain/ServiceGeographic.asmx/GetCityByState") %>',
buildSelect: function (data) {
var retValue = $.parseJSON(data);
var response = $.parseJSON(retValue.d);
var s = '<select id="customer_City" name="customer_City">';
if (response && response.length) {
for (var i = 0, l = response.length; i < l; i++) {
s += '<option value="' + response[i]["Id"] + '">' + response[i]["Descrizione"] + '</option>';
}
}
return s + "</select>";
}
}
},
...
where can i set the parameter to send to the GetCityByState webmethod?
EDIT: I did not highlight that I'm using POST to call webmethod. Even if i tried as Oleg suggested on this link, it doesn't work :(
I think you need ajaxSelectOptions parameter of jqGrid. For example if you need to have the id of the selected row as an additional id parameter sent to webmethod identified by dataUrl you can use data parameter of ajaxSelectOptions in function form:
ajaxSelectOptions: {
type: "GET", // one need allows GET in the webmethod (UseHttpGet = true)
contentType: 'application/json; charset=utf-8',
dataType: "json",
cache: false,
data: {
id: function () {
return JSON.stringify($("#list").jqGrid('getGridParam', 'selrow'));
}
}
}
because in the code above the parameter dataType: "json" are used you should modify the first line of buildSelect from
buildSelect: function (data) {
var retValue = $.parseJSON(data);
var response = $.parseJSON(retValue.d);
...
to
buildSelect: function (data) {
var response = $.parseJSON(data.d);
...
Moreover because you use the line $.parseJSON(data.d) I can suppose that you return the data from the webmethod in the wrong way. Typically the type of return value from the webmethod should be class. You should don't include any call of manual serialization of the returned object. Instead of that some people misunderstand that and declare string as the return type of the webmethod. They makes JSON serialization manually with call of DataContractJsonSerializer or JavaScriptSerializer. As the result the manual serialized data returned as string will be one more time serialized. It's the reason why you can have two calls of $.parseJSON: var retValue = $.parseJSON(data); var response = $.parseJSON(retValue.d);. If you will be use dataType: "json" inside of ajaxSelectOptions and if you would do no manual serialization to JSON in web method and just rejurn the object like it be, you would need to have no call of $.parseJSON at all. You can just use directly data.d:
buildSelect: function (data) {
var response = data.d;
...
I am trying to implement jqGrid in asp.net.
Here is my code.
<script type="text/javascript" src="../js/i18n/grid.locale-en.js"></script>
<script type="text/javascript" src="../js/jquery.jqGrid.min.js"></script>
<script type="text/javascript" src="../js/jquery.jqGrid.src.js"></script>
<script src="../js/plugins/grid.postext.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
jQuery("#tdList").jqGrid({
type: "POST",
datatype: function() {
$.ajax
({
url: "WebService1.asmx/GetDataFromDB",
data: "{}",
datatype: 'json',
contentType: "application/json; charset=utf-8",
});
},
height: "100%",
width: "100%",
forceFit: true,
colNames: ['EmpID', 'Name', 'MGR'],
colModel: [
{ name: 'EmpID', index: 'EmpID', key: true, hidden: true },
{ name: 'Name', index: 'Name', width: 100 },
{ name: 'MGR', index: 'MGR', width: 100 }
],
rowNum: 10,
rowList: [5, 10, 15],
pager: $('#pager'),
sortname: 'EmpID',
viewrecords: true,
sortorder: "desc",
caption: "Customer List"
}).navGrid('#pager', { del: false, add: false, edit: false });
});
and the code behind is
namespace JqGrid_App{
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
{
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
[WebMethod(EnableSession = false)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)]
public string GetDataFromDB()
{
_Default OGetData = new _Default();
return OGetData.GetDataFromDB();
}
}}
The JSONData returning has the format
{
"total":1,
"page":1,
"records":1,
"rows":[
{"id":"6","cell":["Robbie","2"]}
]
}
But the grid is not binding data.
Please help. What I am doing wrong here. I am trying to fix this for last 2 days.
Best Regards,
Mlg
You make too many errors in your code:
You included both query.jqGrid.min.js and query.jqGrid.src.js instead of the usage only one from the files.
Your GetDataFromDB methor return results as string which is wrong. You should return the object having properties total, page, rows and so on. Currently you make manual JSON serialization and the resulting string will be serialized one more time.
You use datatype as function, which was needed many years ago before was introduced new parameters described here for example. Your current implementation datatype function is wrong because it makes asynchronous Ajax call and return before it receive any results from the server. The server results will be discarded.
Your JSON data returned from the server contains two strings for the row of the grid (["Robbie","2"]), but you defines tree columns
...
I can continue...
So I suggest you just look at some other code example which uses ASMX web services with jqGrid. Here for example you can download one working demo. In the answer you will find another demo.
I currently have a JSTree all set up to do the creation and renaming of a new node:
.bind("create_node.jstree", function (NODE, REF_NODE) {
$.ajax({
async: false,
cache: false,
type: 'POST',
url: "ApplicationAJAXHandler.aspx?action=CreateMenuItem&ApplicationID=" + document.getElementById('<%=hdnSelectedAppID.ClientID %>').value + "",
data: {
"operation": "create_node",
"ref": REF_NODE.args[0][0].id,
"title": REF_NODE.rslt.obj[0].innerText
},
success: function (data) {
console.log(data);
}
});
})
.bind("rename_node.jstree", function (NODE, REF_NODE) {
$.ajax({
async: false,
cache: false,
type: 'POST',
url: "ApplicationAJAXHandler.aspx?action=UpdateMenuItem&ApplicationID=" + document.getElementById('<%=hdnSelectedAppID.ClientID %>').value + "",
data: {
"id": createdNodeID,
"title": REF_NODE.rslt.obj[0].innerText
}
});
})
The problem is that my success doesn't seem to get hit when I return an integer ID on the create node, thus I can't set it to a global variable. What exactly do I need to return in the function to get back the ID from the server? I'm simply returning a new integer right now.
I ended up creating a single JSTree object, serializing it, and sending it through the pipe as JSON. Worked like a charm.