Django - HttpResponse 2 query result in JSON format - json

I have 2 query results from the database and try to return it in json format like this.
gt_buffer = ev_ground_truth.objects.filter(alg=_alg, exp=_exp,nFrame=_nframe)
dt_buffer = ev_detection.objects.filter(alg = _alg, exp=_exp, nFrame=_nframe)
json_gt_bb = serializers.serialize('json', gt_buffer)
json_dt_bb = serializers.serialize('json', dt_buffer)
dict_bb_buffer = {'gt': json_gt_bb, 'dt': json_dt_bb}
json_bb_buffer = json.dumps(dict_bb_buffer, ensure_ascii=False)
return HttpResponse(dict_bb_buffer, content_type = "application/json")
And at the front-end,
$.ajax({
url: '/results/get_nframebbs',
data: {
'exp':_exp,
'alg':_alg,
'nframe':data[i]['fields'].nFrame
},
dataType: 'json',
success: function (data) {
alert(data.length)
}
});
However the alert never be called. But if I just serialize 1 query result and return the alert is called successful with a popup.
gt_buffer = ev_ground_truth.objects.filter(alg=_alg, exp=_exp,nFrame=_nframe)
json_gt_bb = serializers.serialize('json', gt_buffer)
return HttpResponse(json_gt_bb, content_type = "application/json")
What did I do wrong?

You have the response as an argument in your success function, not the json data directly. you can access to your data like this:
success: function (response) {
var gt = response.responseJSON.gt;
}

Easy. Just return 2 query result as string and parse at the front-end.
gt_buffer = ev_ground_truth.objects.filter(alg=_alg, exp=_exp,nFrame=_nframe)
dt_buffer = ev_detection.objects.filter(alg = _alg, exp=_exp, nFrame=_nframe)
json_gt_bb = serializers.serialize('json', gt_buffer)
json_dt_bb = serializers.serialize('json', dt_buffer)
dict_bb_buffer = {'gt': json_gt_bb, 'dt': json_dt_bb}
return JsonResponse(dict_bb_buffer, status = 201)
and at the front-end:
dataType: 'json',
success: function (data) {
gt = JSON.parse(data.gt.substring(1,data.gt.length-1));
dt = JSON.parse(data.dt.substring(1,data.dt.length-1));
}

Related

trying to upload Image in mvc web api project using jquery ajax only

I am trying to upload Image but upon running my application my Image parameter is passing null, and I don't know why it is not picking up the file I attached
but in my browser console when I check my image file object that if it is attached or not, it shows that it does attach
but in my controller its passing null
my ajax code where I am passing the image file object,
$('.empOfficialDetails').click(function (ev) {
ev.preventDefault();
var data = new Object();
data.UserName = $('#username').val();
data.UPassword = $('#userpass').val();
data.OfficialEmailAddress = $('#officialemail').val();
data.Departments = $('#departments :selected').text();
data.Designation = $('#designation :selected').text();
data.RoleID = $('#role').val();
data.Role = $('#role :selected').text();
data.ReportToID = $('#reportToID').val();
data.ReportTo = $('#reportTo :selected').text();
data.JoiningDate = $('#joindate').val();
data.IsAdmin = $('#isAdmin :selected').val() ? 1 : 0;
data.IsActive = $('#isActive :selected').val() ? 1 : 0;
data.IsPermanent = $('#isPermanent :selected').val() ? 1 : 0;
data.DateofPermanancy = $('#permanantdate').val();
data.HiredbyReference = $('#hiredbyRef :selected').val() ? 1 : 0;
data.HiredbyReferenceName = $('#refePersonName').val();
data.BasicSalary = $('#basicSalary').val();
data.CurrentPicURL = $('.picture')[0].files; //this is my image file object
//data.EmpID = $('.HiddenID').val();
if (data.UserName && data.UPassword && data.OfficialEmailAddress && data.Departments && data.Designation && data.Role && data.IsAdmin && data.IsPermanent) {
$.ajax({
url: 'http://localhost:1089/api/Employee/EmpOfficialDetails',
type: "POST",
dataType: 'json',
contentType: "application/json",
data: JSON.stringify(data),
enctype: 'multipart/form-data',
beforeSend: function () {
$("#dvRoomsLoader").show();
},
complete: function () {
$("#dvRoomsLoader").hide();
},
success: function (data) {
var ID = parseInt(data);
if (ID > 0) {
//var id = data;
$(".HiddenID").val(data);
//var id = $(".HiddenID").val();
$('#official').css('display', 'block');
$('#official').html("Employees Official details added successfully...!");
$('#official').fadeOut(25000);
$("#dvRoomsLoader").show();
$('.empOfficialDetails').html("Update <i class='fa fa-angle-right rotate-icon'></i>");
}
else {
$('#official').find("alert alert-success").addClass("alert alert-danger").remove("alert alert-success");
}
},
error: function (ex) {
alert("There was an error while submitting employee data");
alert('Error' + ex.responseXML);
alert('Error' + ex.responseText);
alert('Error' + ex.responseJSON);
alert('Error' + ex.readyState);
alert('Error' + ex.statusText);
}
});
}
return false;
});
but in controller on running the code it passes null
public void EmployeeImage(HttpPostedFileBase file)
{
var allowedExtensions = new[] { ".Jpg", ".png", ".jpg", "jpeg" };
var fileName = Path.GetFileName(file.FileName);
var ext = Path.GetExtension(file.FileName); //getting the extension(ex-.jpg)
byte[] bytes;
using (BinaryReader br = new BinaryReader(file.InputStream))
{
bytes = br.ReadBytes(file.ContentLength);
}
if (allowedExtensions.Contains(ext)) //check what type of extension
{
string name = Path.GetFileNameWithoutExtension(fileName); //getting file name without extension
string myfile = name + "_" + ext; //appending the name with id
var path = Path.Combine(System.Web.Hosting.HostingEnvironment.MapPath("~/assets/img/profiles/employeeImages"), myfile); // store the file inside ~/project folder(Img)
file.SaveAs(path);
}
}
public int Emp_OfficialDetails(Employee emp)
{
//SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["AmanraHRMS"].ConnectionString);
var con = DB.getDatabaseConnection();
SqlCommand com = new SqlCommand("sp_InsEmpOfficialDetails", con);
com.CommandType = CommandType.StoredProcedure;
#region Employee Official Details Insert Code block
com.Parameters.AddWithValue("#UserName", emp.UserName);
com.Parameters.AddWithValue("#pass", emp.UPassword);
com.Parameters.AddWithValue("#OfficialEmailAddress", emp.OfficialEmailAddress);
com.Parameters.AddWithValue("#Department", emp.Departments);
com.Parameters.AddWithValue("#Role", emp.Role);
com.Parameters.AddWithValue("#IsAdmin", Convert.ToBoolean(emp.IsAdmin));
com.Parameters.AddWithValue("#Designation", emp.Designation);
com.Parameters.AddWithValue("#ReportToID", emp.ReportToID);
com.Parameters.AddWithValue("#ReportTo", emp.ReportTo);
com.Parameters.AddWithValue("#JoiningDate", Convert.ToDateTime(emp.JoiningDate));
com.Parameters.AddWithValue("#IsPermanent", Convert.ToBoolean(emp.IsPermanent));
com.Parameters.AddWithValue("#DateofPermanancy", Convert.ToDateTime(emp.DateofPermanancy));
com.Parameters.AddWithValue("#IsActive", Convert.ToBoolean(emp.IsActive));
com.Parameters.AddWithValue("#HiredbyReference", Convert.ToBoolean(emp.HiredbyReference));
com.Parameters.AddWithValue("#HiredbyReferenceName", emp.HiredbyReferenceName);
com.Parameters.AddWithValue("#BasicSalary", emp.BasicSalary);
com.Parameters.AddWithValue("#CurrentPicURL", emp.CurrentPicURL);
#endregion
var file = emp.CurrentPicURL;
EmployeeImage(file);
var ID = com.ExecuteScalar();
com.Clone();
return Convert.ToInt32(ID);
}
and in my model class my Image datatype is as
public HttpPostedFileBase CurrentPicURL { get; set; }
I have no Idea what I am doing wrong If anyone who knows about this, your help is highly appreciated my friend
You can't use JSON.stringify to upload a file via AJAX. You need to use the FormData class.
Sending files using a FormData object | MDN
const data = new FormData();
data.append("UserName", $('#username').val());
data.append("UPassword", $('#userpass').val());
...
const file = $('.picture')[0].files[0];
data.append("CurrentPicURL", file, file.name);
...
$.ajax({
url: 'http://localhost:1089/api/Employee/EmpOfficialDetails',
type: "POST",
data: data,
processData: false,
contentType: false,
beforeSend: function () {
...
NB: Unless you need to support Internet Explorer, you might want to use the Fetch API instead of AJAX. This can be much simpler, particularly when combined with async and await.

JSON Query that work in ASP.NET is not working in ASP.NET-Core 3.0 to retun query of fields from DB to User Form

Basically Below Script and related Action Result worked in in ASP.Net but does not work in ASP.Net-Core 2.2 or 3.0.
Apparently Newtosoft JSON is not fully Supported in ASP.Net-Core 3.0 or I do not know how convert for use.
I am not getting an Error ..., The Form just never populates.
I have Copied View and Controllers between .Net version with the same result.
Controller:
public ActionResult GetProductByID1(string id)
{
int AvProdId = Convert.ToInt32(id);
// According id to query the database and get the relevant values.
var query = _context.AvProducts.Where(c => c.AvProductId == AvProdId)
.Select(c =>
new
{
c.AvProductId,
ProductName = c.ProductName,
ProductDesc = c.ProductDesc,
ProductComplexityFac = c.ProductComplexityFac,
ProductComplexityBase = c.ProductComplexityBase,
TotalComplexity = c.TotalComplexity,
Component1Desc = c.Component1Desc,
Component2Desc = c.Component2Desc,
Component3Desc = c.Component3Desc,
Component4Desc = c.Component4Desc,
Component5Desc = c.Component5Desc,
Component6Desc = c.Component6Desc,
Component7Desc = c.Component7Desc,
Component8Desc = c.Component8Desc,
Component9Desc = c.Component9Desc,
Component10Desc = c.Component10Desc,
Component11Desc = c.Component11Desc,
Component12Desc = c.Component12Desc,
Component13Desc = c.Component13Desc,
Component14Desc = c.Component14Desc,
Component15Desc = c.Component15Desc,
ComponentComplexityFac1 = c.ComponentComplexityFac1,
ComponentComplexityFac2 = c.ComponentComplexityFac2,
ComponentComplexityFac3 = c.ComponentComplexityFac3,
ComponentComplexityFac4 = c.ComponentComplexityFac4,
ComponentComplexityFac5 = c.ComponentComplexityFac5,
ComponentComplexityFac6 = c.ComponentComplexityFac6,
ComponentComplexityFac7 = c.ComponentComplexityFac7,
ComponentComplexityFac8 = c.ComponentComplexityFac8,
ComponentComplexityFac9 = c.ComponentComplexityFac9,
ComponentComplexityFac10 = c.ComponentComplexityFac10,
ComponentComplexityFac11 = c.ComponentComplexityFac11,
ComponentComplexityFac12 = c.ComponentComplexityFac12,
ComponentComplexityFac13 = c.ComponentComplexityFac13,
ComponentComplexityFac14 = c.ComponentComplexityFac14,
ComponentComplexityFac15 = c.ComponentComplexityFac15
})
.FirstOrDefault();
return Json(query);
}
Script: from View that populates User form based on DropDownlist Selection
#* Product #1 Calc*#
<script type="text/javascript">
$(function () {
$("#AvProductId").change(function () {
// alert($(this).val() + " " + $(this).find("option:selected").html());
var id = $(this).val();
$.ajax({
type: "Post",
url: '#Url.Action("GetProductByID1", "SizingUserDashBoard")',
data: '{id: "' + id + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
//alert(data.LastName);
//$("#txtAvProdId").val(data.AvProductId);
//$("#txtProductName1").val(data.ProductName);
//$("#txtProductDesc1").val(data.ProductDesc);
//$("#txtProductComplexityFac1").val(data.ProductComplexityFac);
//$("#txtProductComplexityBase1").val(data.ProductComplexityBase);
//$("#txtTotalComplexity1").val(data.TotalComplexity);
//$("#txtComponent1Desc1").val(data.Component1Desc);
//$("#txtComponent2Desc1").val(data.Component2Desc);
//$("#txtComponent3Desc1").val(data.Component3Desc);
//$("#txtComponent4Desc1").val(data.Component4Desc);
//$("#txtComponent5Desc1").val(data.Component5Desc);
//$("#txtComponent6Desc1").val(data.Component6Desc);
//$("#txtComponent7Desc1").val(data.Component7Desc);
//$("#txtComponent8Desc1").val(data.Component8Desc);
//$("#txtComponent9Desc1").val(data.Component9Desc);
//$("#txtComponent10Desc1").val(data.Component10Desc);
//$("#txtComponent11Desc1").val(data.Component11Desc);
//$("#txtComponent12Desc1").val(data.Component12Desc);
//$("#txtComponent13Desc1").val(data.Component13Desc);
//$("#txtComponent14Desc1").val(data.Component14Desc);
//$("#txtComponent15Desc1").val(data.Component15Desc);
#* $("#TestProdDesc12").val(data.Component12Desc);
$("#TestProdDesc13").val(data.Component13Desc);
$("#Prod1Compnent2Desc").val($("#txtComponent2Desc1").val());
$("#Prod1Compnent3Desc").val($("#txtComponent3Desc1").val());*#
//$("#TestProdDesc12").val($("#txtComponent12Desc1").val());
//$("#TestProdDesc13").val($("#txtComponent13Desc1").val());
$("#DescProduct_1").val(data.ProductName);
$("#Prod1Compnent1Desc").val(data.Component1Desc);
$("#Prod1Compnent2Desc").val(data.Component2Desc);
$("#Prod1Compnent3Desc").val(data.Component3Desc);
$("#Prod1Compnent4Desc").val(data.Component4Desc);
$("#Prod1Compnent5Desc").val(data.Component5Desc);
$("#Prod1Compnent6Desc").val(data.Component6Desc);
$("#Prod1Compnent7Desc").val(data.Component7Desc);
$("#Prod1Compnent8Desc").val(data.Component8Desc);
$("#Prod1Compnent9Desc").val(data.Component9Desc);
$("#Prod1Compnent10Desc").val(data.Component10Desc);
$("#Prod1Compnent11Desc").val(data.Component11Desc);
$("#Prod1Compnent12Desc").val(data.Component12Desc);
$("#Prod1Compnent13Desc").val(data.Component13Desc);
$("#Prod1Compnent14Desc").val(data.Component14Desc);
$("#Prod1Compnent15Desc").val(data.Component15Desc);
$("#Compnent1Desc").val(data.Component1Desc);
$("#Compnent2Desc").val(data.Component2Desc);
$("#Compnent3Desc").val(data.Component3Desc);
$("#Compnent4Desc").val(data.Component4Desc);
$("#Compnent5Desc").val(data.Component5Desc);
$("#Compnent6Desc").val(data.Component6Desc);
$("#Compnent7Desc").val(data.Component7Desc);
$("#Compnent8Desc").val(data.Component8Desc);
$("#Compnent9Desc").val(data.Component9Desc);
$("#Compnent10Desc").val(data.Component10Desc);
$("#Compnent11Desc").val(data.Component11Desc);
$("#Compnent12Desc").val(data.Component12Desc);
$("#Compnent13Desc").val(data.Component13Desc);
$("#Compnent14Desc").val(data.Component14Desc);
$("#Compnent15Desc").val(data.Component15Desc);
$("#Prod1ComponentComplexityFac1_1").val(data.ComponentComplexityFac1);
$("#Prod1ComponentComplexityFac2_1").val(data.ComponentComplexityFac2);
$("#Prod1ComponentComplexityFac3_1").val(data.ComponentComplexityFac3);
$("#Prod1ComponentComplexityFac4_1").val(data.ComponentComplexityFac4);
$("#Prod1ComponentComplexityFac5_1").val(data.ComponentComplexityFac5);
$("#Prod1ComponentComplexityFac6_1").val(data.ComponentComplexityFac6);
$("#Prod1ComponentComplexityFac7_1").val(data.ComponentComplexityFac7);
$("#Prod1ComponentComplexityFac8_1").val(data.ComponentComplexityFac8);
$("#Prod1ComponentComplexityFac9_1").val(data.ComponentComplexityFac9);
$("#Prod1ComponentComplexityFac10_1").val(data.ComponentComplexityFac10);
$("#Prod1ComponentComplexityFac11_1").val(data.ComponentComplexityFac11);
$("#Prod1ComponentComplexityFac12_1").val(data.ComponentComplexityFac12);
$("#Prod1ComponentComplexityFac13_1").val(data.ComponentComplexityFac13);
$("#Prod1ComponentComplexityFac14_1").val(data.ComponentComplexityFac14);
$("#Prod1ComponentComplexityFac15_1").val(data.ComponentComplexityFac15);
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Failed to retrieve Products.');
}
});
});
});
</script>
You need to lowercase initial letter of data.property and change the url like below:
#section Scripts{
<script type="text/javascript">
$(function () {
$("#AvProductId").change(function () {
var id = $(this).val();
$.ajax({
type: "Post",
url: '#Url.Action("GetProductByID1", "SizingUserDashBoard")'+'?id='+id,
//data: '{id: "' + id + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
console.log(data);
$("#DescProduct_1").val(data.productName);
$("#Prod1Compnent1Desc").val(data.component1Desc);
$("#Prod1Compnent2Desc").val(data.component2Desc);
$("#Prod1Compnent3Desc").val(data.component3Desc);
$("#Prod1Compnent4Desc").val(data.component4Desc);
$("#Prod1Compnent5Desc").val(data.component5Desc);
$("#Prod1Compnent6Desc").val(data.component6Desc);
$("#Prod1Compnent7Desc").val(data.component7Desc);
$("#Prod1Compnent8Desc").val(data.component8Desc);
$("#Prod1Compnent9Desc").val(data.component9Desc);
$("#Prod1Compnent10Desc").val(data.component10Desc);
$("#Prod1Compnent11Desc").val(data.component11Desc);
$("#Prod1Compnent12Desc").val(data.component12Desc);
$("#Prod1Compnent13Desc").val(data.component13Desc);
$("#Prod1Compnent14Desc").val(data.component14Desc);
$("#Prod1Compnent15Desc").val(data.component15Desc);
$("#Prod1ComponentComplexityFac1_1").val(data.componentComplexityFac1);
$("#Prod1ComponentComplexityFac2_1").val(data.componentComplexityFac2);
$("#Prod1ComponentComplexityFac3_1").val(data.componentComplexityFac3);
$("#Prod1ComponentComplexityFac4_1").val(data.componentComplexityFac4);
$("#Prod1ComponentComplexityFac5_1").val(data.componentComplexityFac5);
$("#Prod1ComponentComplexityFac6_1").val(data.componentComplexityFac6);
$("#Prod1ComponentComplexityFac7_1").val(data.componentComplexityFac7);
$("#Prod1ComponentComplexityFac8_1").val(data.componentComplexityFac8);
$("#Prod1ComponentComplexityFac9_1").val(data.componentComplexityFac9);
$("#Prod1ComponentComplexityFac10_1").val(data.componentComplexityFac10);
$("#Prod1ComponentComplexityFac11_1").val(data.componentComplexityFac11);
$("#Prod1ComponentComplexityFac12_1").val(data.componentComplexityFac12);
$("#Prod1ComponentComplexityFac13_1").val(data.componentComplexityFac13);
$("#Prod1ComponentComplexityFac14_1").val(data.componentComplexityFac14);
$("#Prod1ComponentComplexityFac15_1").val(data.componentComplexityFac15);
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Failed to retrieve Products.');
}
});
});
});
</script>
}
Result:

how to pagination JSONResult in MVC with ajax url data loading?

I have a problem in pagination with a json result data in MVC.
Below code is my ajax data loading:
jQuery.ajax({
url: "/Products/Search",
type: "POST",
dataType: "json",
success: function (data) {
displayData(data);
},
error: function (errdata, errdata1, errdata2) { $('#ProductList').html("Error in connect to server" + errdata.responseText); }
and my controller JsonResult is below:
public JsonResult List()
{
tbl = db.tblProducts;
return Json(tbl, JsonRequestBehavior.AllowGet);
}
I can recive data from above ajax data loading successfully, but I can't pagination it.
Please help me.
Thank you.
There is no code for Pagination,Do you want to do client side pagination or server side
Thinking your devloping an ASP.Net MVC application
Server side pagnation : You can load the specific number of records alone.
Using Skip and Take functionlitys
public JsonResult GetOrders(int pagesize, int pagenum)
{
var query = Request.QueryString;
var dbResult = db.Database.SqlQuery<Order>(this.BuildQuery(query));
var orders = from order in dbResult
select new Order
{
ShippedDate = order.ShippedDate,
ShipName = order.ShipName,
ShipAddress = order.ShipAddress,
ShipCity = order.ShipCity,
ShipCountry = order.ShipCountry
};
var total = dbResult.Count();
orders = orders.Skip(pagesize * pagenum).Take(pagesize);
var result = new
{
TotalRows = total,
Rows = orders
};
return Json(result, JsonRequestBehavior.AllowGet);
}
Client side pagination : Load the entire records to your view from there implement pagination
Sample code : http://jsfiddle.net/rniemeyer/5xr2x/
Database db = new Database();
public int PageSize = 5;
public int VisiblePageCount = 5;
public JsonResult Search(int page = 1)
{
var model = new ModelName();
var tbl = db.tblProducts;
var renderedScheduleItems =(tbl.Skip((page - 1) * PageSize)
.Take(PageSize)
.ToList());
model.Products = renderedScheduleItems;
model.PagingDetail = new PagingDetail()
{
CurrentPage = page,
ItemsPerPage = PageSize,
TotalItems = items.Count,
VisiblePageCount = VisiblePageCount
};
return Json(model, JsonRequestBehavior.AllowGet);
}

How to Access each elements in the following json output

Here is my j-son output and i want to access inner elements element.
how should i do that?
i have tried to access them in the following way
data[10];
but it didn't worked
public JsonResult ShowEventsList()
{
using (EventSchedularEntities db = new EventSchedularEntities())
{
var EventsList = from evnt in db.Events
select new
{
id = evnt.EventID,
Subject = evnt.EventName,
Description = evnt.EventDesc,
StartTime = evnt.EventDateBegin,
EndTime = evnt.EventDateEnd,
Color = evnt.Importance,
};
List<object[]> LstEvents = new List<object[]>();
foreach (var ev in EventsList)
{
LstEvents.Add(new object[] { ev.id, ev.Subject, ev.Description,DateTime.Parse(ev.StartTime.ToString()).ToString("M/dd/yyyy hh:mm").Replace("-", "/"), DateTime.Parse(ev.EndTime.ToString()).ToString("M/dd/yyyy hh:mm").Replace("-", "/"), ev.Color });
}
return Json( LstEvents, JsonRequestBehavior.AllowGet);
}
}
$.ajax({
type: "POST",
url: "../EventScheduler/ShowEventsList",
datatype: "json",
success: function (result)
{
var data = JSON.parse(result);
alert(data);
}

JqGrid trying to send large data from server to grid but getting:Error during serialization or deserialization using the JSON JavaScriptSerializer

I have a problem I am receiving large amount of data from the server and am then converting it to Json format, to be then viewed in JqGrid. It works for small amount of data say for example 200 rows but when doing this for 10000 rows it throws the following error
System.InvalidOperationException: Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property
I have tried using the javascript serializer and set it to maxjsonLenght = int32.MaxValue but still no luck
Following is my code please give me suggestions with examples how I can fix this? Thanks all!
GridConfig
public JqGridConfig(String db, String jobGroup, String jobName, String detailTable, String filterBatchControl, String filterDate, String filterTime, int page)
{
var entityhelper = new EntityHelper();
var s = new JsonSerializer();
try
{
//Populate Grid Model, Column Names, Grid Column Model, Grid Data
entityhelper.PopulateDetailGridInit(db, jobGroup, jobName, detailTable, filterBatchControl, filterDate, filterTime);
JqGridDetailAttributes = entityhelper.GridDetailAttributes;
JqGridDetailColumnNames = entityhelper.GridDetailColumnNames;
//JqGridDetailsColumnNamesForExport = entityhelper.GridDetailColumnNamesForExport;
JqGridDetailColumnModel = entityhelper.GridDetailColumnModel;
//Dynamic Data
JqGridDynamicDetailData = entityhelper.GridDetailData;
#region Column Model
foreach (KeyValuePair<String, JqGridColModel> kvp in entityhelper.GridDetailColumnModel)
{
s.Serialize(kvp.Key, kvp.Value.Attributes);
}
JqGridDetailColumnModelJson = s.Json();
#endregion
#region Concrete data. 1. List<dynamic> populated, 2. Convert to Json String, 3: Convert back to List<Detail>
JqGridDetailData = JsonSerializer.ConvertDynamicDetailsToJson(JqGridDynamicDetailData); // this is where the error occurs
}
catch (Exception ex)
{
//TODO: Logging
System.Diagnostics.Debug.WriteLine(ex.Message);
}
}
Json Serializer
public static IList<Detail> ConvertDynamicDetailsToJson(IList<dynamic> list)
{
if (list.Count == 0)
return new List<Detail>();
var sb = new StringBuilder();
var contents = new List<String>();
sb.Append("[");
foreach (var item in list)
{
var d = item as IDictionary<String, Object>;
sb.Append("{");
foreach (KeyValuePair<String, Object> kvp in d)
{
contents.Add(String.Format("{0}: {1}", "\"" + kvp.Key + "\"", JsonConvert.SerializeObject(kvp.Value)));
}
sb.Append(String.Join(",", contents.ToArray()));
sb.Append("},");
}
sb.Append("]");
//remove trailing comma
sb.Remove(sb.Length - 2, 1);
var jarray = JsonConvert.DeserializeObject<List<Detail>>(sb.ToString());
return jarray;
}
Controller that return Json result from server
public JsonResult DetailGridData(TheParams param)
{
dynamic config= "";
switch (param.JobGroup)
{
case "a":
config = new BLL.abcBLL().GetDetailGridData("rid", "desc", 1, 20, null,
param.FilterBatchControl,
param.JobName, param.DetailTable,
param.JobGroup, param.BatchDate,
param.Source);
break;
}
return Json(config, JsonRequestBehavior.AllowGet); // this reurns successfully json result
}
View where the Jqgrid exists and does not populate the grid
<script type="text/javascript">
var jobGroup = '#ViewBag.JobGroup';
var jobName = '#ViewBag.JobName';
var detailTable = '#ViewBag.DetailTable';
var filterBatchControl = '#ViewBag.FilterBatchControl';
var controlDate = '#ViewBag.ControlDate';
var controlTime = '#ViewBag.ControlTime';
var source = '#ViewBag.DetailSource';
var page = '#ViewBag.page';
function loadDetailData() {
var param = new Object();
param.BatchDate = controlDate;
param.BatchTime = controlTime;
param.JobGroup = jobGroup;
param.JobName = jobName;
param.DetailTable = detailTable;
param.FilterBatchControl = filterBatchControl;
param.Source = source;
param.page = page;
window.parent.loadingDetailsHeader();
$.ajax({
url: "/control/detailgriddata",
dataType: 'json',
type: 'POST',
data: param,
async: false,
success: function (response) {
try {
jgGridDetailColumnNames = response.JqGridDetailColumnNames;
//jqGridDetailColumnData = response.JqGridDetailData;
jqGridDetailColumnData = response.config;
$('#detailGrid').jqGrid('setGridParam', {colNames: jgGridDetailColumnNames});
$('#detailGrid').jqGrid('setGridParam', {data: jqGridDetailColumnData}).trigger('reloadGrid');
parent.loadingDetailsHeaderComplete();
}
catch(e) {
window.parent.loadingDetailsHeaderException(e.Message);
}
return false;
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
}
function exportdetails(date) {
var param = new Object();
param.db = source;
param.jobGroup = jobGroup;
param.jobName = jobName;
param.detailTable = detailTable;
param.filterBatchControl = filterBatchControl;
param.filterDate = date;
param.filterTime = "NULL";
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: '#Url.Action("ExportDetailsCsv", "Control")',
dataType: 'json',
data: $.toJSON(param),
async: false,
success: function (response) {
window.location.assign(response.fileName);
},
error: function (xhr, ajaxOptions, thrownError) {
alert("Details Export Exception: " + xhr.status);
}
});
}
//<![CDATA[
$(document).ready(function () {
'use strict';
$(window).resize(function () {
$("#detailGrid").setGridWidth($(window).width());
}).trigger('resize');
var dgrid = $("#detailGrid");
$('#detailGrid').jqGrid('clearGridData');
loadDetailData();
dgrid.jqGrid({
datatype: 'json',
data: jqGridDetailColumnData,
colNames: jgGridDetailColumnNames,
colModel: [ #Html.Raw(#ViewBag.ColModelDetail) ],
rowNum: 25,
rowList: [25, 50, 100],
pager: '#detailPager',
gridview: true,
autoencode: false,
ignoreCase: true,
viewrecords: true,
altrows: false,
autowidth: true,
shrinkToFit: true,
headertitles: true,
hoverrows: true,
height: 300,
onSelectRow: function (rowId) {
//This is a demo dialog with a jqGrid embedded
//use this as the base for viewing detail data of details
//$('#dialogGrid').dialog();
//gridDialog();
},
loadComplete: function (data) {},
gridComplete: function (data) {
//if (parseInt(data.records,10) < 50) {
$('#detailPager').show();
//} else {
//$('#detailPager').show();
//}
}
}).jqGrid('navGrid', '#detailPager', { edit: false, add: false, del: false, search: false }, {});
});
//]]>
</script>
<table id="detailGrid">
<tr>
<td />
</tr>
</table>
<div id="detailPager"></div>
<div id="dialogGrid"></div>
Probably you should consider to use server side paging instead of returning 10000 rows to the client? Server side paging of SQL data can be implemented much more effectively as client side paging (sorting of large non-indexed data in JavaScript program).
One more option which you have is the usage of another JSON serializer. For example it can be protobuf-net, ServiceStack.Text (see here too), Json.NET and other. In the way you can additionally improve performance of your application comparing with JavaScriptSerializer.