JqGrid in asp.net is not binding - asp.net

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.

Related

Can i use angular kendo grid in my asp.net project

I am currently using asp.net 4 with bootstrap 3 in my project, Here i used bootstap typeahead for autocomplete textbox so i want that once user select data from autocomplete list so that time it should do ajax call and angular kendo ajax call and should bind returned data in success event.
Below is my code:
updater: function (item) {
$('[id*=hdnHomeSearch]').val(map[item]);
populateSearchItem();
return item;
}
This is my typoahead method where i am containing textbox autocomplete selected data by user.
and in populateSearchItem method i want to call angularjs kendo grid which is below:
<script src="../scripts/jquery-1.11.3.js" type="text/javascript"></script>
<script src="../Content/dist/js/bootstrap.min.js" type="text/javascript"></script>
<script src="../scripts/angularjs.min.js" type="text/javascript"></script>
<script src="../Content/dist/js/kendo.all.min.js" type="text/javascript"></script>
<script src="../scripts/typoAhead.js" type="text/javascript"></script>
<div ng-app="app" ng-controller="MyCtrl">
<div kendo-grid k-options="gridOptions" k-rebind="gridOptions" k-pageable='{ "pageSize": 2, "refresh": true, "pageSizes": true }'></div>
</div>
<script type="text/javascript">
angular.module("app", ["kendo.directives"]).controller("MyCtrl", function ($scope, $http) {
$scope.gridOptions = {
columns: [{ field: "EmployeeKey" }, { field: "FirstName"}],
dataSource: {
transport: {
read: {
type: "POST",
url: '<%=ResolveUrl("Search.aspx/GetData1") %>',
dataType: "json",
contentType: "application/json"
},
parameterMap: function (options, operation) {
return JSON.stringify(options);
}
},
pageSize: 5,
schema: {
data: "Data",
errors: "Errors",
total: "Total",
model: {
id: "EmployeeKey",
fields: {
EmployeeKey: { editable: false, defaultValue: 0 },
FirstName: { type: "string", validation: { required: true} }
}
}
}
}
}
});
</script>
but after using this getting error text in console that is angular modulerr.
so this script method i want to use inside populateSearchItem method.
All suggestions are welcome.

Kendo AutoComplete Empty Filter in Querystring - serverfiltering

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));
}

why is my jqGrid is empty eventhough json data is present

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:

jqgrid form editing editoptions select ajax add parameter

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;
...

Sending JSON object successfully to ASP.NET WebMethod, using jQuery

I've been working on this for 3 hours and have given up.
I am simply trying to send data to an ASP.NET WebMethod, using jQuery.
The data is basically a bunch of key/value pairs. So I've tried to create an array and adding the pairs to that array.
My WebMethod (aspx.cs) looks like this (this may be wrong for what I'm building in JavaScript, I just don't know):
[WebMethod]
public static string SaveRecord(List<object> items)
{
...
}
Here is my sample JavaScript:
var items = new Array;
var data1 = { compId: "1", formId: "531" };
var data2 = { compId: "2", formId: "77" };
var data3 = { compId: "3", formId: "99" };
var data4 = { status: "2", statusId: "8" };
var data5 = { name: "Value", value: "myValue" };
items[0] = data1;
items[1] = data2;
items[2] = data3;
items[3] = data4;
items[4] = data5;
Here is my jQuery AJAX call:
var options = {
error: function(msg) {
alert(msg.d);
},
type: "POST",
url: "PackageList.aspx/SaveRecord",
data: { 'items': items },
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function(response) {
var results = response.d;
}
};
jQuery.ajax(options);
I get the error:
Invalid JSON primitive: items.
So, if I do this:
var DTO = { 'items': items };
and set the data parameter like this:
data: JSON.stringify(DTO)
Then I get this error:
Cannot convert object of type \u0027System.String\u0027 to type \u0027System.Collections.Generic.List`1[System.Object]\u0027
In your example, it should work if your data parameter is:
data: "{'items':" + JSON.stringify(items) + "}"
Keep in mind that you need to send a JSON string to ASP.NET AJAX. If you specify an actual JSON object as jQuery's data parameter, it will serialize it as &k=v?k=v pairs instead.
It looks like you've read it already, but take another look at my example of using a JavaScript DTO with jQuery, JSON.stringify, and ASP.NET AJAX. It covers everything you need to make this work.
Note: You should never use JavaScriptSerializer to manually deserialize JSON in a "ScriptService" (as suggested by someone else). It automatically does this for you, based on the specified types of the parameters to your method. If you find yourself doing that, you are doing it wrong.
When using AJAX.NET I always make the input parameter just a plain old object and then use the javascript deserializer to covert it to whatever type I want. At least that way you can debug and see what type of object the web method in is recieving.
You need to convert your object to a string when using jQuery
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="sm" runat="server" EnablePageMethods="true">
<Scripts>
<asp:ScriptReference Path="~/js/jquery.js" />
</Scripts>
</asp:ScriptManager>
<div></div>
</form>
</body>
</html>
<script type="text/javascript" language="javascript">
var items = [{ compId: "1", formId: "531" },
{ compId: "2", formId: "77" },
{ compId: "3", formId: "99" },
{ status: "2", statusId: "8" },
{ name: "Value", value: "myValue"}];
//Using Ajax.Net Method
PageMethods.SubmitItems(items,
function(response) { var results = response.d; },
function(msg) { alert(msg.d) },
null);
//using jQuery ajax Method
var options = { error: function(msg) { alert(msg.d); },
type: "POST", url: "WebForm1.aspx/SubmitItems",
data: {"items":items.toString()}, // array to string fixes it *
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function(response) { var results = response.d; } };
jQuery.ajax(options);
</script>
And the Code Behind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Serialization;
using System.Web.Script.Services;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace CustomEquip
{
[ScriptService]
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static void SubmitItems(object items)
{
//break point here
List<object> lstItems = new JavaScriptSerializer().ConvertToType<List<object>>(items);
}
}
}
The following is a code snippet from our project - I had trouble with not wrapping the object as a string and also with Date values - hopefully this helps someone:
// our JSON data has to be a STRING - need to send a JSON string to ASP.NET AJAX.
// if we specify an actual JSON object as jQuery's data parameter, it will serialize it as ?k=v&k=v pairs instead
// we must also wrap the object we are sending with the name of the parameter on the server side – in this case, "invoiceLine"
var jsonString = "{\"invoiceLine\":" + JSON.stringify(selectedInvoiceLine) + "}";
// reformat the Date values so they are deserialized properly by ASP.NET JSON Deserializer
jsonString = jsonString.replace(/\/Date\((-?[0-9]+)\)\//g, "\\/Date($1)\\/");
$.ajax({
type: "POST",
url: "InvoiceDetails.aspx/SaveInvoiceLineItem",
data: jsonString,
contentType: "application/json; charset=utf-8",
dataType: "json"
});
The server method signature looks like this:
[WebMethod]
public static void SaveInvoiceLineItem(InvoiceLineBO invoiceLine)
{
Decorate your [WebMethod] with another attribute:
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
I believe this is in System.Web.Services.Scripting...
see link http://www.andrewrowland.com/article/display/consume-dot-net-web-service-with-jquery
This is the way you define your data (JSON)
data: { 'items': items },
and the this the way it should be
data: '{ items: " '+items +' "}',
basically you are serializing the parameter.

Resources