jqGrid postdata sends null values (mvc3 asp/net) - asp.net

jqGrid doesn't send postdata to my controller. I tried all provided solutions on stackoverflow, buy apparently I'm making error(s) somewhere. So here is the code:
function refreshGrid() {
alert('CompanyNamePart=' + $("#CompanyNamePart").val()); // to check if this is correct value
$("#list").trigger('reloadGrid');
return false;
}
$(function () {
var grid = jQuery("#list").jqGrid({
datatype: 'json',
caption: 'Transaction Log',
postdata: {
CompanyNamePart: function () { return $("#CompanyNamePart").val(); },
UsernamePart: function () { return $("#UsernamePart").val(); },
},
url: '#Url.Action("GetTransactionLogData")',
mtype: 'GET',
colNames: ['Ref.', 'TradeDate', 'Status'],
colModel: [
{ name: 'Reference', index: 'Reference', width: '60' },
{ name: 'TradeDate', index: 'TradeDate', width: '70' },
{ name: 'Status', index: 'Status', width: '80' }
],
pager: $('#pager'),
rowNum: 10,
height: '100%'
});
});
On Controller side I have simple code:
[HttpGet]
public ActionResult GetTransactionLogData(string sidx, string sord, int page, int rows, string CompanyNamePart, string UsernamePart)
{ return Json(null); }
and in Debugging mode when I call refreshGrid() by clicking a button I get one alert to confirm me that it reads correctly value of textfield, and after that it refreshes the grid. I receive call of controller, but values for CompanyNamePart and UsernamePart variables are all null, even though I filled them.
I tried another solution for postdata section with another approach, first I created functions that return needed values and put them in postdata section of grid:
function getCompanyNamePartVal() {
return $("#CompanyNamePart").val();
}
function getUsernamePartVal() {
return $("#UsernamePart").val();
}
... in jqgrid definition
postdata: {
CompanyNamePart: getCompanyNamePartVal(),
UsernamePart: getUsernamePartVal(),
},
but with no success.
When I checked Firebug, I could see that jqGrid is not sending postdata values:
Get Parameters caught by Firebug
_ 1340696638960
_search false
nd 1340696638955
page 1
rows 10
sidx
sord asc
What am I doing wrong?

The parameter is called postData, not postdata. Don't forget that javascript is a case sensitive language. So try like this:
postData: {
CompanyNamePart: function () { return $("#CompanyNamePart").val(); },
UsernamePart: function () { return $("#UsernamePart").val(); }
}
Also notice that I removed a trailing comma after the UsernamePart function that you had in your code and which produces invalid javascript. Some more sensitive browsers might not accept it.

$("#grid").jqGrid({
url: "/DocumentoBalanza/GetBalanzaEmpresaMes",
//postData: JSON.stringify(formDataParam),
postData : {
id: function () { return formDataParam.id; },
strDate: function () { return formDataParam.strDate; },
},
datatype: 'json',
mtype: 'GET',
public JsonResult GetBalanzaEmpresaMes(string sidx, string sord, int page, int rows, int id, string strDate)
Code OK.

Related

bootstrapTable onLoadError's param [status], post url is ASP.NET WebMethod

now,I'm try to use bootstrapTable to load my data that using ASP.NET WebMethod.
$.ajax(): url is set like this: "url:mydata.aspx/GetData"
and this is work fine.
in the other way:
$('#mytab').bootstrapTable({
method: 'post',
contentType: "application/x-www-form-urlencoded",
url:"mydata.aspx/GetData",
toolbar: '#toolbar',
striped: true,
dataField: "res",
pageNumber: 1,
pagination:true,
queryParamsType:'limit',
queryParams:queryParams,
sidePagination:'server',
pageSize:10,
pageList:[5,10,20,30],
showRefresh:true,
showColumns:true,
clickToSelect: true,
toolbarAlign:'right',
buttonsAlign:'right',
toolbar:'#toolbar',
columns:[
{
title:'全选',
field:'select',
checkbox:true,
width:25,
align:'center',
valign:'middle'
},
{
title:'ID',
field:'ID',
visible:false
},
{
title:'登录名',
field:'LoginName',
sortable:true
},
{
title:'姓名',
field:'Name',
sortable:true
},
{
title:'手机号',
field:'Tel',
},
{
title:'邮箱',
field:'Email'
},
{
title:'注册日期',
field:'CreateTime',
sortable:true
},
{
title:'状态',
field:'Attribute',
align:'center',
formatter:operateFormatter
}
],
responseHandler:function(res){
return res;
},
onLoadError: function(status){
alert("error"+status);
}
})
function operateFormatter(value,row,index){
。。。
}
function queryParams(params){
return{
pageSize: params.limit,
pageIndex:params.pageNumber,
content:$('#search_name').val()
}
}
ASP.NET API code here
[WebMethod]
public static string GetData(int pageSize, int pageIndex, string content)
{
return "{total:200,rows:[{......}]}";
}
But now I got an error code:
[error200]has been alerted.
I want to know [onLoadError]'s error status's map
200:XXXX
400:XXXX
500:XXXX
bootstrapTable document has no error status map information.
please help........
Paste your JSON data into myjson.com and really make sure it's good json (without errors). Then post a JSFiddle with a subset of your code and using the url from the myjson.com link it provides.

Google chart using JSON - Format issue - ASP.net - "Table has no columns”

I am seeing 2 types of JSON format out there and getting really confused.
I a trying to do the following:
I have an excel model with a range
Type RV
MRC 10
CRC 20
CVA 30
OpRisk 0
Using ExCelToWeb vba function from cDataSet (http://ramblings.mcpher.com/Home/excelquirks/json/excel-json-conversion), I convert this range to a JSON string. Output is as follows:
{ "cDataSet":[
{
"Type":"MRC",
"RV":10
},
{
"Type":"CRC",
"RV":20
},
{
"Type":"CVA",
"RV":30
},
{
"Type":"OpRisk",
"RV":0
}
]}
I save this into a text file called myData.json
In Default.aspx.cs, I have
[WebMethod]
public static String GetDataJSON(){
String myvar = File.ReadAllText("C:\\Users\\Serge\\Downloads\\GoogleChartExample\\GoogleChartExample\\myData.json");
return myvar;
}
I call the function from Java Script in Default.aspx
google.load('visualization', '1', { packages: ['corechart'] });
google.setOnLoadCallback(drawChart);
function drawChart() {
$.ajax({
type: 'POST',
dataType: 'json',
url: 'Default.aspx/GetDataJSON',
contentType: 'application/json',
data: {},
async: false,
success:
function (response) {
console.log(response.d);
var data = new google.visualization.DataTable(response.d);
var csv = google.visualization.dataTableToCsv(data);
console.log(csv);
new google.visualization.ColumnChart(document.getElementById('myChart1')).draw(data, { title: "MyChart1" });
},
error: function (jqXHR, textStatus, errorThrown) {
alert(textStatus + '\n' + errorThrown);
if (!$.browser.msie) {
console.log(jqXHR);
}
}
});
}
=> console.log(response.d) outputs my JSON string exactly as intended
=> console.log(csv) does not output anything
=> the google chart outputs a red box saying “Table has no columns”
I understand that there are 2 types of JSON format. The one that google has in its example has "cols": [ , and "rows": [ . Does it mean that Google Chart / Dataset is not compatible with my format? Is there anyway for me to convert from one to the other?
Would I be better not to use JSON and export from excel -> cvs => a C# array -> a google dataset?
Thank you very much.
Serge

How can I set the total number of data items in my grid using a function?

I've tried various ways to set the total number of records in the Kendo-UI Web Grid, without success.
I'm kind of lost on where I spend the amount processed in ajax, already assigns the total value in the schema for 4 to see if it happens more paging did not work, just shows the two records and it shows that there are more pages.
If anyone could help me I would be very grateful!
...
transport: {
read: function (option) {
$.ajax({
url: '<?=$view->encode('ctrl.php?turma=lista_turma');?>',
data:{
skip: option.data.skip,
take: option.data.take,
pageSize: option.data.pageSize,
page: option.data.page,
sorting: JSON.stringify(option.data.sort),
filter: JSON.stringify(option.data.filter)
},
success: function (result) {
option.success(JSON.parse(result));
},
error: function (result) {
alert(result);
}
},
schema: {
data: 'data',
total: function (data) {
return 4;
},
/*total: function (result) {
alert('aqui');
result = result.d || result;
return 4;
},*/
model: { id: "id_turma" },
fields: {
id_turma: { validation: { required: true } },
nome_turma: { validation: { required: true } },
sigla_turma: { validation: { required: true, max:12 } }
}
}
},
pageable: true,
serverPaging: true,
serverFiltering: true,
serverSorting: true,
batch: true,
pageSize: 2
});
I'm not sure what you're trying to do with all those "eval" statements in your code. This looks like you're overcomplicating things a lot.
If you do server-side paging, the total should be returned from the server since the client typically doesn't know how many more records there are. If your response contains a property "total", then this should work:
schema: {
total: "total" // total is returned in the "total" field of the response
}
or this, if you want to use a function:
schema: {
total: function(response) {
return response.total; // total is returned in the "total" field of the response
}
}
Both taken from the docs:
http://docs.kendoui.com/api/framework/datasource#configuration-schema.total
Here's a working example: http://jsfiddle.net/lhoeppner/y6KdK/

Kendo UI Grid Fires CRUD Operations multiple times

I've seen this problem in many places but I can't seem to find a solution. So I have defined a Kendo grid with CRUD operations the thing is that the previous fired operations get fired again.
Say you delete entry X and then you add entry Y, the create operation fires and after that the delete operation (for X - which has been deleted) fires again. Same thing if you first create an element and then edit another, it edits the 2nd element and then it re-fires the 1st create statement and inserts a duplicate for the 1st inserted element. If you go on an on with several operations a nightmare happens with all the other previous operations being fired and sent to the controller.
My grid is:
function InitializeIPAddressesGrid(userID) {
selectedUserID = userID;
$(".ipAddresses").kendoGrid({
dataSource: IPAdressesDataSource,
sortable: {
mode: "single",
allowUnsort: false
},
remove: function (e) {
this.refresh();
var canDelete = confirm("Are you sure you want to delete this record?");
if (!canDelete) {
e.preventDefault();
}
},
height: 420,
resizable: true,
pageable: {
refresh: true,
pageSize: 10
},
selectable: "row",
toolbar: ["create"],
editable:{mode: "inline", confirmation:false} ,
columns: [{
field: "IpAddress",
title: "IP Address"
},
{
field: "Status",
title: "Status"
},
{
field: "LockedUntil",
title: "Locked until",
template: "#=kendo.toString(LockedUntil, 'yyyy/MM/dd' )#"
},
{ command: ["edit", "destroy"], title: " ", width: "180px" }
]
});
}
var IPAdressesDataSource = new kendo.data.DataSource({
type: "json",
serverPaging: true,
serverSorting: true,
serverFiltering: true,
pageSize: 10,
//scrollable:false,
transport: {
read: {
url: websiteRootUrl + '/PortalAuthorization/GetIPAddressesList',
},
update: {
url: websiteRootUrl + "/PortalAuthorization/UpdateIP",
dataType: "json",
type: 'POST',
complete: function (e) {
if (e.status != 200) {
alert(eval('(' + e.responseText + ')').Message);
}
}
},
create: {
url: websiteRootUrl + "/PortalAuthorization/CreateIP",
dataType: "json",
type: 'POST',
complete: function (e) {
if (e.status != 200) {
alert(eval('(' + e.responseText + ')').Message);
}
}
},
destroy: {
url: websiteRootUrl + "/PortalAuthorization/DeleteIP",
dataType: "json",
type: 'DELETE',
complete: function (e) {
if (e.status != 200) {
alert(eval('(' + e.responseText + ')').Message);
}
}
},
parameterMap: function (options, operation) {
if (operation == "update" && options) {
return {ipAddress: options.IpAddress ,
status: options.Status ,
lockedUntil: kendo.toString(options.LockedUntil, 'yyyy/MM/dd' ),
pkey: options.ID,
databaseID: selectedDatabaseID };
}
else
if (operation == "destroy" && options)
{
return {
databaseID: selectedDatabaseID,
pkey: options.ID,
userIDParam: selectedUserID
};
}
else
if (operation == "create" && options) {
return {ipAddress: options.IpAddress ,
status: options.Status ,
lockedUntil: kendo.toString(options.LockedUntil, 'yyyy/MM/dd' ),
pkey: options.ID,
userIDParam: selectedUserID,
databaseID: selectedDatabaseID };
}
else
{
options.databaseID = selectedDatabaseID;
options.userID = selectedUserID;
return options;
}
}
},
schema: {
model: {
id: "ID",
fields: {
IpAddress: { type: "string" },
Status: { type: "string" },
LockedUntil: { type: "date" }
}
},
data: function (data) {
return data.Items;
},
total: function (data) {
return data.TotalCount;
}
}
});
My controllers are:
public object UpdateIP(int databaseID, long pkey, string status, string lockedUntil, string ipAddress)
{
var database = [...];
DynamicDataRepository repository = [...];
string query = "...";
repository.ExecuteNonQuery(query);
return new HttpResponseMessage(HttpStatusCode.OK);
}
public object DeleteIP(int databaseID, long pkey, int? userIDParam)
{
var database = [...];
DynamicDataRepository repository = [...];
string query = "...";
repository.ExecuteNonQuery(query);
return new HttpResponseMessage(HttpStatusCode.OK);
}
public object CreateIP(int databaseID, long? pkey, string status, string lockedUntil, string ipAddress, int? userIDParam)
{
var database = [...];
DynamicDataRepository repository = [...];
string query = "...";
repository.ExecuteNonQuery(query);
return new HttpResponseMessage(HttpStatusCode.OK);
}
Do you have any ideea? where I've done something wrong? thanks in advance. P.S. the queries in the controllers work fine.
I fixed the problem, followed OnaBai's suggestion of returning the Updated/Created entity, and in the case of a Delete I returned the ID of the deleted entry.
public object UpdateIP(int databaseID, long pkey, string status, string lockedUntil, string ipAddress)
{
var database = [...];
DynamicDataRepository repository = [...];
string query = [...];
IPList updatedIP = new IPList { ID = pkey, IpAddress = ipAddress, Status = status, LockedUntil = DateTime.Today };
return Json(updatedIP, JsonRequestBehavior.AllowGet);
// return new HttpResponseMessage(HttpStatusCode.OK);
}
Only one mention: in the case of a CREATE, the method didn't seem to work so what I did is in the .complete event of the CREATE operation I did a ipGrid.dataSource.read();
ipGrid.refresh(); - so the operation doesn't repeat itself. ( I read that in this case there might be problem with the model definition - setting the ID field - but I did set that one). Many thanks to OnaBai

jqgrid webmethod : failed to save row

ByVal datax As ObjectI'm trying to use ASP.NET with webmethod to retrieve data and save data for jqgrid.
I can retrieve data from the webmethod but no luck to do the save.
The server side seems never get my post data. Would someone please help?
grid code:
$('#list99').jqGrid({
datatype: function(postdata) {
$.ajax({
url: 'dbtest.aspx/getdata',
editurl: 'dbtest.aspx/updatedb',
type: 'POST',
data: '{}',
dataType: "json",
contentType: "application/json; charset=utf-8",
error: function(data, textStatus) {
alert('Error loading json');
},
success: function(data, st) {
if (st == 'success') {
var grid = $("#list99");
var gridData = JSON.parse(data.d);
grid.clearGridData();
for (var i = 0; i < gridData.length; i++) {
grid.addRowData(i + 1, gridData[i]);
}
}
$("#list99").jqGrid('navGrid', '#pager99', { add: true, edit: true, del: true });
}
});
},
type: 'POST',
editurl: 'dbtest.aspx/updatedb',
colNames: ['customerid', 'customername'],
colModel: [
{ name: 'customerid', index: 'customerid', width: 80, align: 'left', editable: true, edittype: 'text' },
{ name: 'customername', index: 'customername', width: 120, align: 'left', editable: true, edittype: 'text'}],
pager: $('#pager99'),
rowNum: 5,
rowList: [10],
sortname: 'customerid',
sortorder: 'desc',
viewrecords: true,
//width: 300
autowidth: true
});
server side code:
Public Class customer
Public customerid As String
Public customername As String
End Class
<System.Web.Services.WebMethod()> _
Public Shared Function getdata() As String
Dim c1 As New customer
Dim c2 As New customer
c1.customerid = "1"
c1.customername = "pete"
c2.customerid = "2"
c2.customername = "joah"
Dim lstcustomer As New List(Of customer)
lstcustomer.Add(c1)
lstcustomer.Add(c2)
Dim jsonserial As New JavaScriptSerializer
Dim result As String
result = jsonserial.Serialize(lstcustomer)
Return result
End Function
<System.Web.Services.WebMethod()> _
Public Shared Function updatedb(ByVal datax As Object) As String
//attempt to do save
End Function
The function updatedb just never being called after i clicked "sumbit" after add/edit/delete.
After that i checked with firebug and i got the error message:
"Invalid web service call, missing value for parameter: 'data'."
I've also tried to add the following:
jQuery.extend(jQuery.jgrid.edit, {
ajaxEditOptions: { contentType: "application/json" },
recreateForm: true,
serializeEditData: function(data) {
//alert('in2');
//alert(postData.customerid);
//alert(JSON.stringify(postData));
if (data.customerid == undefined) { data.customerid = null; }
var postData = { 'data': data };
//alert(postData.customerid);
return JSON.stringify(postData);
}
});
It still didnt work =(
I don't recommend you ever use datatype defined as function especially if you do just jQuery.ajax to communicate with the server. jqGrid provide many ways to customize data which will be send to the server (see serializeGridData callback and ajaxGridOptions option of jqGrid for example) and to change the server response before the server response will be processed by jqGrid (beforeProcessing callback for example). The current code use addRowData to fill the data. It' the slowest way to fill the grid which I know. Moreover you call navGrid on every loading of the data instead of calling it once directly after the grid will be created. All other calls will be just ignored. You can find many examples how to use web servicing together with jqGrid. Look at the answer for example
Your current code mix the options of jQuery.ajax with the options of jqGrid. You placed editurl option of jqGrid into the list of options of $.ajax.
One more important error is the usage of correct names of variables in updatedb method. You use currently datax As Object instead of usage customerid and customername as parameters.

Resources