Issue with JSON data from .NET to jqGrid - c#

I have a dynamic function to generate table data to JSON which kinda works, now I try to add it to a list in .NET however I can't get this right past few days, anybody knows what I do wrong?
the output is like this:
[{"itemsSerialized":"{\"id\":1,\"name\":\"Medical 1\",\"city\":\"Kiev\",\"instituteTypeId\":0}"},{"itemsSerialized":"{\"id\":2,\"name\":\"Medical 2\",\"city\":\"Kherson\",\"instituteTypeId\":0}"}]
which should be without the "itemsSerialized":", I understand where it comes from, but dont understand why a object declaration suddenly shows up in my JSON string
my C# code:
Object itemsSerialized = "";
foreach (DataRow r in _data.Rows)
{
DynamicClass dynamicClass = new DynamicClass();
dyna.ConvertRowToCustomer(r, out dynamicClass);
DynamicClassList.Add(dynamicClass);
var iSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
itemsSerialized = JsonConvert.SerializeObject(dynamicClass.Property.properties);
Object itemsSerialized2 = JsonConvert.DeserializeObject(xJSON);
Gridist.Add(new { itemsSerialized });
}
with jQuery I have this to load the data into the jQGrid:
$.ajax({
type: "POST",
contentType: "application/json",
url: "dataServices/objects.asmx/InvokeData",
data: "{ 'q': 'med&1'}",
dataType: 'json',
success: function (result) {
var str = result.d;
alert(result.d);
$("#jqGrid_2")[0].addJSONData(result.d);
}
});
The return I have now as:
{"id":1,"name":"Medical 1","city":"Kiev","instituteTypeId":0},{"id":2,"name":"Medical 2","city":"Kherson","instituteTypeId":0}
UPDATE INTERNAL AJAX VERSION:
mtype: 'POST',
contentType: "application/json",
url: "dataServices/objects.asmx/InvokeData",
ajaxGridOptions: {
contentType: 'application/json; charset=utf-8'
},
postData: JSON.stringify({q: "med&1"}),
loadonce: true,
dataType: 'json',
jsonReader: {
root: function (obj) {
alert(obj.d);
return obj.d;
},
page: "",
total: "",
records: function (obj) {
return obj.d.length;
},
},
gridview: true,
loadError: function (xhr, status, error) {
alert('load error: ' + error);
},
And is being written away in the first column from first and only row....
What I do wrong and how I get the itemsSerialized out

First of all the server response
{
"id": 1,
"name": "Medical 1",
"city": "Kiev",
"instituteTypeId": 0
},
{
"id": 2,
"name": "Medical 2",
"city": "Kherson",
"instituteTypeId": 0
}
is wrong. Correct data should be array of items like
[
{
"id": 1,
"name": "Medical 1",
"city": "Kiev",
"instituteTypeId": 0
},
{
"id": 2,
"name": "Medical 2",
"city": "Kherson",
"instituteTypeId": 0
}
]
Another JSON response which you posted contains two problems. 1) "itemsSerialized":" prefix 2) the value of all items are strings
[
{
"itemsSerialized": "{\"id\":1,\"name\":\"Medical 1\",\"city\":\"Kiev\",\"instituteTypeId\":0}"
},
{
"itemsSerialized": "{\"id\":2,\"name\":\"Medical 2\",\"city\":\"Kherson\",\"instituteTypeId\":0}"
}
]
The reason of the first problem is the usage of
Gridist.Add(new { itemsSerialized });
instead of
Gridist.Add(itemsSerialized);
The reason of the second problem is unneeded usage of JsonConvert.SerializeObject. What you should do is something like
Gridist.Add(dynamicClass.Property.properties);
instead of
itemsSerialized = JsonConvert.SerializeObject(dynamicClass.Property.properties);
Gridist.Add(new { itemsSerialized });

Related

DataTables error loading ajax source data

I am getting the following error when trying to load DataTables ajax sourced data:
DataTables warning: table id=report-table - Ajax error. For more information about this error, please see http://datatables.net/tn/7
Below is my DataTables html:
<table id="report-table" class="display nowrap" style="width:100%">
<thead>
<tr>
<th>Page ID</th>
<th>Schema</th>
<th>Name</th>
<th>Last Modified</th>
<th>Last Modified User</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Page ID</th>
<th>Schema</th>
<th>Name</th>
<th>Last Modified</th>
<th>Last Modified User</th>
</tr>
</tfoot>
</table>
Below is my DataTables javascript:
$('#report-table').DataTable({
"ajax": data,
"columns": [
{
"data": "PageId",
"orderable": true
},
{
"data": "SchemaName",
"orderable": false
},
{
"data": "Name",
"orderable": true
},
{
"data": "LastModified",
"orderable": true
},
{
"data": "LastModifiedUser",
"orderable": true
},
],
"order": [[3, "desc"]]
});
Below is the confirmed json my C# controller is returning for the DataTables ajax data:
{
"data":[
{
"PageId":"foo",
"SchemaName":"foo",
"Name":"foo",
"LastModified":"foo",
"LastModifiedUser":"foo"
},
{
"PageId":"foo",
"SchemaName":"foo",
"Name":"foo",
"LastModified":"foo",
"LastModifiedUser":"foo"
},
{
"PageId":"foo",
"SchemaName":"foo",
"Name":"foo",
"LastModified":"foo",
"LastModifiedUser":"foo"
}
]
}
The error seems to be related to the JSON format, but not sure what is wrong?
EDIT:
Adding full javascript code:
<script>
$(function () {
$("button#report-form-submit").click(function () {
event.preventDefault();
var data = $("form#report-form").serialize();
$.ajax({
type: "POST",
url: "#Url.Action("GetReportJson", "Report")",
data: data,
dataType: 'json',
beforeSend: function (data) {
},
success: function (data) {
// Report DataTables Init
// ===========================================
$('#report-table').DataTable({
"ajax": data,
"columns": [
{
"data": "PageId",
"orderable": true
},
{
"data": "SchemaName",
"orderable": false
},
{
"data": "Name",
"orderable": true
},
{
"data": "LastModified",
"orderable": true
},
{
"data": "LastModifiedUser",
"orderable": true
},
],
"order": [[3, "desc"]]
});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
},
complete: function (data) {
}
});
});
});
</script>
Your <script> block should look like this to initialize your data for your Data Tables:
<script>
$(function () {
$("button#report-form-submit").click(function () {
event.preventDefault();
var data = $("form#report-form").serialize();
$.ajax({
type: "POST",
url: "#Url.Action("GetReportJson", "Report")",
data: data,
dataType: "json",
method: "post",
beforeSend: function (data) {
},
success: function (data) {
// Report DataTables Init
// ===========================================
$('#report-table').DataTable({
"data":data,
"columns": [
{
"data": "PageId",
"orderable": true
},
{
"data": "SchemaName",
"orderable": false
},
{
"data": "Name",
"orderable": true
},
{
"data": "LastModified",
"orderable": true
},
{
"data": "LastModifiedUser",
"orderable": true
},
],
"order": [[3, "desc"]]
});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
},
complete: function (data) {
}
});
});
});
</script>
the data source should be an array of arrays that contains the data in the tbody
say
data = [
["foo","foo","foo","foo","foo"],
["foo","foo","foo","foo","foo"],
["foo","foo","foo","foo","foo"]
];
see the example [https://datatables.net/examples/data_sources/js_array.html][1]
additionally, use data: data.data instead of "ajax" : data
As your JSON response is an object but not an array, specify the ajax to get the JsonResponse.data as below:
"ajax": {
"url": /* Your Get Data API url */,
"dataSrc": function (json) {
return json.data;
},
},
OR
"ajax": {
"url": /* Your Get Data API url */,
"dataSrc": "data"
},
JQuery answer
Updated: Change from json.data to data as Post Owner changed requirement.
data: data
$.ajax({
type: "POST",
url: "#Url.Action("GetReportJson", "Report")",
data: data,
dataType: 'json',
beforeSend: function (data) {
},
success: function (data) {
// Report DataTables Init
// ===========================================
$('#report-table').DataTable({
"data": data,
... // Remaining DataTable configurations
});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
},
complete: function (data) {
}
});
Output
Reference
ajax - DataTables.net

Data received in controller from ajax is NULL?

I am receiving null in both ProductData and ProductDetailsData when data is sent from ajax to controller. What could be the issue ?
IN CONTROLLER :
public bool UpdateProduct(Entity_Product ProductData, Entity_ProductDetails ProductDetailsData)
{
return Json(DrugService.UpdateProduct(ProductData, ProductDetailsData));
}
IN JS FILE :
$(document).on("click", "#btn_update", function () {
//Prepare data
var ProductDataArray = [];
var ProductDetailsDataArray = [];
ProductDataArray.push({
"Name": $('#txt_drugname').val(),
"CommercialName": $('#txt_drugcommercialname').val(),
"PackageType": $("#dd_packagetype option:selected").val(),
"DrugType": $("#dd_drugtype option:selected").val(),
"DrugCode": $('#txt_drugcode').val(),
"ProductId": $('#hdn_productid').val(),
"Administration": $('#txt_administration').val(),
"Manufacturer": $('#txt_manufacturer').val(),
"Price": $('#txt_price').val(),
"Strength": $('#txt_stregnth').val(),
"StregnthUnit": $("#dd_stregnthunit option:selected").val(),
"Barcode": $('#txt_barcode').val(),
"IsEnabled": $("#dd_isenabled option:selected").val(),
"UpdatedOn": new Date(),
"UpdatedBy": 'UserNme',
});
ProductDetailsDataArray.push({
"ProductId": $('#hdn_productid').val(),
"ProductDetailsId": $('#hdn_productdetailid').val(),
"Length": $('#txt_Legnth').val(),
"Width": $('#txt_width').val(),
"Height": $('#txt_height').val(),
"ConversionRate": $('#txt_conversion').val(),
"DrugForm": $("#dd_drugform option:selected").val(),
"StoredAs": $("#dd_storedas option:selected").val()
});
//Send data
$.ajax({
url: '/Drug/UpdateProduct/',
type: 'POST',
data: { 'ProductData': ProductDataArray, 'ProductDetailsData': ProductDetailsDataArray },
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (data, textStatus, jqXHR) {
}
});
});
You have several issues in both AJAX and controller action method:
1) You're tried to pass arrays into data using contentType set to application/json without doing JSON.stringify() first, therefore it won't work since array required to pass either as JSON string or use traditional: true setting.
2) The action method parameter types are not set to array but a single entity class like viewmodel, you need to declare an object instead of array.
3) The controller action uses bool return type which should use JsonResult (or ActionResult) type.
Based from those mistakes mentioned above, try to use setup like below:
jQuery
$(document).on("click", "#btn_update", function () {
var ProductDataArray = {
"Name": $('#txt_drugname').val(),
"CommercialName": $('#txt_drugcommercialname').val(),
"PackageType": $("#dd_packagetype option:selected").val(),
"DrugType": $("#dd_drugtype option:selected").val(),
"DrugCode": $('#txt_drugcode').val(),
"ProductId": $('#hdn_productid').val(),
"Administration": $('#txt_administration').val(),
"Manufacturer": $('#txt_manufacturer').val(),
"Price": $('#txt_price').val(),
"Strength": $('#txt_stregnth').val(),
"StregnthUnit": $("#dd_stregnthunit option:selected").val(),
"Barcode": $('#txt_barcode').val(),
"IsEnabled": $("#dd_isenabled option:selected").val(),
"UpdatedOn": new Date(),
"UpdatedBy": 'UserNme',
};
var ProductDetailsDataArray = {
"ProductId": $('#hdn_productid').val(),
"ProductDetailsId": $('#hdn_productdetailid').val(),
"Length": $('#txt_Legnth').val(),
"Width": $('#txt_width').val(),
"Height": $('#txt_height').val(),
"ConversionRate": $('#txt_conversion').val(),
"DrugForm": $("#dd_drugform option:selected").val(),
"StoredAs": $("#dd_storedas option:selected").val()
};
$.ajax({
url: '/Drug/UpdateProduct/',
type: 'POST',
data: JSON.stringify({ 'ProductData': ProductDataArray, 'ProductDetailsData': ProductDetailsDataArray }),
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (data, textStatus, jqXHR) {
// do something
}
});
});
Controller Action
[HttpPost]
public ActionResult UpdateProduct(Entity_Product ProductData, Entity_ProductDetails ProductDetailsData)
{
return Json(DrugService.UpdateProduct(ProductData, ProductDetailsData));
}

jQuery datatable using ajax POST method to send custom object

I want to send custom object to my controller method with jquery datatables default parameters for paging, sorting, searching and # of records binding.
The issue is :
When I Post object to server using datatable ajax it successfully post my object and also send parameters for length, start and draw BUT stops sending parameters for sorting n searching.
When I do GET request it sends all parameters but not only my custom object and obviously it should not
I want to send custom object with datatable defaults parameters for paging and sorting
WHAT IS THE SOLUTION FOR IT ?
here is code:
$('#example').DataTable({
"processing": true,
"serverSide": true,
"ajax": {
"url": "/Color/Fetch",
"type": 'Post',
// "dataType": "json"
data: { color: $scope.colorSearch }
// dataSrc: 'data'
},
"columns": [
{ "data": "Active" },
{ "data": "Company_Id" },
{ "data": "Id" },
{ "data": "IsActive" },
{ "data": "Name" }
]
});
Controller action:
public JsonResult Fetch(Color color, int draw, int start, int length)
{
string search = Request.QueryString["search[value]"];
int sortColumn = -1;
string sortDirection = "asc";
if (length == -1)
{
length = 90;
}
// note: we only sort one column at a time
if (Request.QueryString["order[0][column]"] != null)
{
sortColumn = int.Parse(Request.QueryString["order[0][column]"]);
}
if (Request.QueryString["order[0][dir]"] != null)
{
sortDirection = Request.QueryString["order[0][dir]"];
}}
Try to use the following approach:
$('#example').DataTable({
"processing": true,
"serverSide": true,
/*
"ajax": {
"url": "/Color/Fetch",
"type": 'Post',
// "dataType": "json"
data: { color: $scope.colorSearch }
// dataSrc: 'data'
},
*/
"ajaxSource": "/Color/Fetch",
//fnServerData method used to inject the parameters into the AJAX call sent to the server-side
"fnServerData": function (sSource, aoData, fnCallback) {
aoData.push({ "name": "color", "value": "Blue" }); // Add some extra data to the sender
$.getJSON(sSource, aoData, function (json) {
/* Do whatever additional processing you want on the callback, then tell DataTables */
fnCallback(json);
});
},
"columns": [
{ "data": "Active" },
{ "data": "Company_Id" },
{ "data": "Id" },
{ "data": "IsActive" },
{ "data": "Name" }
]
});

Receving null value in controller action via AJAX

Salaamun Alekum
I am getting null in controller action via an AJAX request:
var ProjectPermission = [{
"CreatedBy": "Akshay"
},{
"CreatedBy": "Kumar"
},{
"CreatedBy": "ETC"
}]
$.ajax({
url: '/api/Projects/AssignProjectPermissions',
type: 'POST',
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify({
ProjectPermission: ProjectPermission
}),
success: function (data) {
alert(data);
},
// processData: false //Doesn't help
});
My C# controller:
[System.Web.Http.HttpPost, System.Web.Http.HttpGet]
public string AssignProjectPermissions(ProjectPermission[] ProjectPermission)
{
I am getting null in ProjectPermission. I already tried other answers but none of them worked for me. These were the posts I checked:
How to get Ajax posted Array in my C# controller?
Ajax post to ASP.net MVC controller - object properties are null
Thank You
You should not be using GET and POST on the same method first of all, just use POST in this case. That aside you do not need the property name. You are putting your array inside of an object. Your method is expecting an array.
var ProjectPermission = [{ CreatedBy: "Akshay" },
{ CreatedBy: "Kumar" },
{ CreatedBy: "ETC" }]
$.ajax({
url: '/api/Projects/AssignProjectPermissions'
, type: 'POST'
, contentType: 'application/json'
, dataType: 'json'
, data: JSON.stringify(ProjectPermission) //<------------issue here
, success: function (data)
{ alert(data); }
//, processData: false
});

Display NO Data when Ajax success is empty or null

I have a WebMethod, which is populating a JQuery DataTable with some initial values. I have a drop down list, which calls the WebMethod and try to populate it with different values. My problem, is if the JSON data is null (or '') then i get JSON.parse: unexpected end of data.
Now, I can check the length of the object using if(msg.d.length !- '' { build the table} ) However, if the length is null (''), then i never go into the build table, and therefore cant present that there is no data / no records.
How can I ensure that if the JSON string/object is null ('') that DataTables still presents No Records found etc...?
$('#ddBICS').change(function (e) {
var val = $('#dd option:selected').text();
msgDateDetail(val);
});
function msgDateDetail(value) {
$.ajax({
type: "POST",
url: "Default.aspx/MsgDateDetail",
cache: false,
data: JSON.stringify({ searchValue: value }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
var data = JSON.parse(msg.d);
var asInitVals = new Array();
otblMsgDateDetail = $("#tblMsgDateDetail").dataTable({
"sDom": "<'row-fluid'<'span6'T><'span6'f>r>t<'row-fluid'<'span6'i><'span6'p>>",
"oTableTools": {
"aButtons": [
"copy",
"print",
{
"sExtends": "collection",
"sButtonText": 'Save <span class="caret" />',
"aButtons": ["csv", "xls", "pdf"]
}
]
},
"aaData": data
})
}
});
}
msg could be null or undefined, just checking for the variable will tell you that. Also since you're using JQuery you could check if d is an array with the isArray JQuery method.
if(msg && msg.d && $.isArray(msg.d) && msg.d.length > 0) {
// build the table
}else{
// data is empty
}
Within your above method you would do the following.
function msgDateDetail(value) {
$('#tblMsgDate
$.ajax({
type: "POST",
url: "Default.aspx/MsgDateDetail",
cache: false,
data: JSON.stringify({ searchValue: value }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
var asInitVals = new Array();
var data = (msg && msg.d && $.isArray(msg.d))? msg.d : new Array();
otblMsgDateDetail = $("#tblMsgDateDetail").dataTable({
"sDom": "<'row-fluid'<'span6'T><'span6'f>r>t<'row-fluid'<'span6'i><'span6'p>>",
"oTableTools": {
"aButtons": [
"copy",
"print",
{
"sExtends": "collection",
"sButtonText": 'Save <span class="caret" />',
"aButtons": ["csv", "xls", "pdf"]
}
]
},
"aaData": data
})
}
});
}
The documentation for the jquery method is located on jquery.com http://api.jquery.com/jQuery.isArray/
For this to work make sure that your Default.aspx/MsgDateDetail returns application/json for the content type. To do this in the aspx file you do the following:
Response.ContentType = "application/json"
You must do this before you do any Response.Write
You should the length like this
if(msg.d.length !=0) { // Try this
//-- build the table
}

Categories

Resources