How to set the maxJsonLength property? - javascript

I have a JsonResult returning 29833 records, of a CustomerID and a CustomerName. I am trying to load this into an AutoComplete, but I keep getting this error.
Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property.
I did some digging around on the subject and came across this link here
So I read over it and the answer provided didn't work out for me and then the next suggestion looked promising until I looked more at the code and came to the conclusion that it won't work for me because I am using JQuery Ajax to get the JsonResult. Now I am not sure what to do, here is the JQuery that I am using
function LoadCustomers() {
$.ajax({
type: "GET",
url: "/Test/GetAllCustomers",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data, textStatus, jqXHR) {
ShowCustomers(data);
}
});
}
function ShowCustomers(custdata) {
$("#acCustomers").kendoAutoComplete({
dataSource: custdata,
filter: "startswith",
placeholder: "Select Customer...",
dataTextField: "CustomerName"
});
}
I even tried just populating a grid but to no avail. Any idea's on how I can get this to work properly going about it the way I am going about it? I think as a last resort I would have to change my stored procedure around and pass in characters on every keyup event, I don't know if that would be a good idea or maybe it is, I don't know. Either way I sure could use some help or direction
EDIT
The reason that this is not a duplicate based on the supplied link is because I am not working server-side, I am working Client-Side.
EDIT 2
Here is my JsonResult
public JsonResult GetAllCustomers(string name)
{
PGDAL dal = new PGDAL();
List<Customer> lst = dal.GetAllCustomers();
return Json(lst, JsonRequestBehavior.AllowGet);
}

One thing I have learned from some experience is that it seems like ASP.net MVC ignores any JSON Max value you place in the Web.config file. I normally just do the following:
var JsonSerializer = new JavaScriptSerializer();
JsonSerializer.MaxJsonLength = Int32.MaxValue;
As Paul Swetz linked up top, you might find some more resources in managing the MAX value but I am pretty sure this will be the most widely accepted answer.

Related

Ajax Parameter Being Received as {string[0[} in MVC Controller

First of all, I have never successfully built an AJAX call that worked. This is my first real try at doing this.
I am working on building a function to update existing records in a SQL database. I am using ASP.NET Core (.NET 6) MVC but I also use JavaScript and jQuery. I cannot have the page refresh, so I need to use ajax to contact the Controller and update the records.
I have an array that was converted from a NodeList. When I debug step by step, the collectionsArray looks perfectly fine and has data in it.
//Create array based on the collections list
const collectionsArray = Array.from(collectionList);
$.ajax({
method: 'POST',
url: '/Collections/UpdateCollectionSortOrder',
data: collectionsArray,
})
.done(function (msg) {
alert('Sent');
});
However, when I run the application and debug the code, the array is received in the Controller as {string[0]}.
Here is the method which is in the Controller, with my mouse hovered over the parameter:
Do not pay attention to the rest of the code in the controller method. I have not really written anything in there of importance yet. I plan to do that once the data is correctly transferred to the Controller.
I have tried dozens of ideas including what you see in the Controller with the serialize function, just to see if it processes the junk data that is getting passed, but it hasn't made a difference.
I have been Googling the issue & reading other StackOverflow posts. I've tried things like adding/changing contentType, dataType, adding 'traditional: true', using JSON.stringify, putting 'data: { collections: collectionsArray }' in a dozen different formats. I tried processing it as a GET instead of POST, I tried using params.
I am out of ideas. Things that have worked for others are not working for me. What am I doing wrong? I'm sure it's something minor.
UPDATE: Here is the code which explains what the collectionList object is:
//Re-assign SortID's via each row's ID value
var collectionList = document.querySelectorAll(".collection-row");
for (var i = 1; i <= collectionList.length; i++) {
collectionList[i - 1].setAttribute('id', i);
}
What I am doing is getting a list off the screen and then re-assigning the ID value, because the point of this screen is to change the sort order of the list. So I'm using the ID field to update the sort order, and then I plan to pass the new IDs and names to the DB, once I can get the array to pass through.
UPDATE: SOLVED!
I want to post this follow up in case anyone else runs into a similar issue.
Thanks to #freedomn-m for their guidance!
So I took the NodeList object (collectionList) and converted it to a 2-dimensional array, pulling out only the fields I need, and then I passed that array onto the controller. My previous efforts were causing me to push all sorts of junk that was not being understood by the system.
//Create a 2-dimensional array based on the collections list
const collectionArray = [];
for (var i = 0; i < collectionList.length; i++) {
collectionArray.push([collectionList[i].id, collectionList[i].children[1].innerHTML]);
}
$.ajax({
method: 'POST',
url: '/Collections/UpdateCollectionSortOrder',
data: { collections: collectionArray }
})
.done(function (msg) {
alert('Sent');
});
2-d array is coming through to the Controller successfully

Accessing JSON parsed object

So here is my JS code:
$(document).ready(function() {
$.ajax({
url: "/",
type:"POST",
beforeSend: function (xhr) {
var token = $('meta[name="csrf_token"]').attr('content');
if (token) {
return xhr.setRequestHeader('X-CSRF-TOKEN', token);
}
},
success:function(data){
console.log(data);
},error:function(){
console.log("error!!!!");
}
});
});
And this is what I get in my console:
Object { all_creations: "[{"id":"2","user_id":"2","title":"D…" }
But now I'd like to do something like:
console.log(data.user_id)
But this return nothing..
Same for:
console.log(data['all_creations'].user_id)
console.log(data['all_creations'][0].user_id)
console.log(data[0].user_id)
...
I am using laravel5 btw and this JSON object is return by the toJson() function. (if this is any help)
I know this question has already been answered millions times but for some reason I cannot get it work on my project... I am not a pro in Javascript or anything related to it like JSON. Ajax, JSON remain for me a source of intense pain. I hope to get it one day... seriously ^^
If anything, this is a rough guide to how you can access your data:
Object { all_creations: "[{"id":"2","user_id":"2","title":"D…" }
^^^^^^^^ ^
The marked areas indicate that data is a standard object, so it has already been parsed.
Object { all_creations: "[{"id":"2","user_id":"2","title":"D…" }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
The inner portion says that data.all_creations is a property that contains a string value.
Object { all_creations: "[{"id":"2","user_id":"2","title":"D…" }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
The string value itself seems to contain a JSON encoded value, so you would need to parse that first:
var creations = JSON.parse(data.all_creations);
Then, from the string value you can see it contains an array with an object as the first element.
alert(creations[0].user_id) // 2
I feel like your best bet here would be to test it in Chrome and use the F12 developer tools to see what is coming back from the server. Maybe check the request in the Network tab or try to figure out the proper way to retrieve the user_id in the console.
If confused take a look at some F12 Chrome developer tools tutorials.

CRM 2011 API call for a view GUID by name

I'm trying to pull back the GUID of a view to set a default lookup value in javascript. The rest of my code works if I hard code the variables, but that's not good development practice (though, pulling back a unique identifier by querying on a non-unique identifier isn't great either, but its better). I'm not sure how to form the ajax call though.
Here is a shell of what I am working with, I just don't know what to put at the end of /CRMServices/2011/OrganizationData.svc/ to get the proper record from the API. The Views are savedquery entities, so /savedquerySet makes sense but I'm not sure how to tell it to look up by name. I've not used this API a lot, and the documentation is confusing for me.
var b = Xrm.Page.context.getServerUrl() + "/XRMServices/2011/OrganizationData.svc/savedquerySet (<something here not sure what>)";
$.ajax({
type: "GET",
datatype: "json",
url: b,
beforeSend: function (a) {
a.setRequestHeader("Accept", "application/json")
},
success: function (a) {
var b = a.d;
SetGuid(b.SavedQueryIdUnique); // defined function
}
})
the field I am trying to query on is Name.
Help is very appreciated. This is in CRM 2011 UR 8 or so
Your REST query should look something like this:
/SavedQuerySet?$select=SavedQueryId&$filter=Name%20eq%20'YOUR VIEW NAME HERE'
The SavedQuerySet name is case sensitive, as well as the attribute name in the select (and filter) clause.
See the MSDN documentation on the ODATA endpoint for details.

Using JSON to store multiple form entries

I'm trying to create a note taking web app that will simply store notes client side using HTML5 local storage. I think JSON is the way to do it but unsure how to go about it.
I have a simple form set up with a Title and textarea. Is there a way I can submit the form and store the details entered with several "notes" then list them back?
I'm new to Javascript and JSON so any help would be appreciated.
there are many ways to use json.
1> u can create a funciton on HTML page and call ajax & post data.
here you have to use $("#txtboxid").val(). get value and post it.
2> use knock out js to bind two way.and call ajax.
here is simple code to call web app. using ajax call.
var params = { "clientID": $("#txtboxid") };
$.ajax({
type: "POST",
url: "http:localhost/Services/LogisticsAppSuite.svc/Json/GetAllLevelSubClients",
contentType: 'application/json',
data: JSON.stringify(params),
dataType: 'json',
async: false,
cache: false,
success: function (response) {
},
error: function (ErrorResponse) {
}
I have written a lib that works just like entity framework. I WILL put it here later, you can follow me there or contact me to get the source code now. Then you can write js code like:
var DemoDbContext = function(){ // define your db
nova.data.DbContext.call(this);
this.notes=new nova.data.Repository(...); // define your table
}
//todo: make DemoDbContext implement nova.data.DbContext
var Notes = function(){
this.id=0; this.name="";
}
//todo: make Note implement nova.data.Entity
How to query data?
var notes = new DemoDbContext().notes.toArray(function(data){});
How to add a note to db?
var db = new DemoDbContext();
db.notes.add(new Note(...));
db.saveChanges(callback);
Depending on the complexity of the information you want to store you may not need JSON.
You can use the setItem() method of localStorage in HTML5 to save a key/value pair on the client-side. You can only store string values with this method but if your notes don't have too complicated a structure, this would probably be the easiest way. Assuming this was some HTML you were using:
<input type="text" id="title"></input>
<textarea id="notes"></textarea>
You could use this simple Javascript code to store the information:
// on trigger (e.g. clicking a save button, or pressing a key)
localStorage.setItem('title', document.getElementById('title').value);
localStorage.setItem('textarea', document.getElementById('notes').value);
You would use localStorage.getItem() to retrieve the values.
Here is a simple JSFiddle I created to show you how the methods work (though not using the exact same code as above; this one relies on a keyup event).
The only reason you might want to use JSON, that I can see, is if you needed a structure with depth to your notes. For example you might want to attach notes with information like the date they were written and put them in a structure like this:
{
'title': {
'text':
'date':
}
'notes': {
'text':
'date':
}
}
That would be JSON. But bear in mind that the localStorage.setItem() method only accepts string values, you would need to turn the object into a string to do that and then convert it back when retrieving it with localStorage.getItem(). The methods JSON.stringify will do the object-to-string transformation and JSON.parse will do the reverse. But as I say this conversion means extra code and is only really worth it if your notes need to be that complicated.

jQuery and long int ids

I've faced with a next problem:
In our database we have objects with ids, like 4040956363970588323.
I'm writing some client-wizard on jQuery for interacting with such objects. Client receives base data about objects trough an Ajax request, like:
$.ajax({
url: "/api/pages/",
type: "get",
dataType: "json",
data: {"id": site_id},
success: function(data){
if (data.success){
for (var pidx in data.pages){
console.log(data.pages[pidx].id);
var li = $('<li class="ui-widget-content"></li>');
var idf = $('<input type="hidden" id="pid" value="{0}"/>'.format(data.pages[pidx].id))
var urlf = $('<input type="hidden" id="purl" value="{0}"/>'.format(data.pages[pidx].url))
li.text(data.pages[pidx].title);
li.append(idf);
li.append(urlf);
$("#selectable_pages_assign").append(li);
}
pages_was = $("#selectable_pages_assign>li");
}
else
updateTips(data.message);
},
error: function(){
updateTips("Internal erro!");
}
})
So, as you see I send data like JSON object (a bit of server code):
return HttpResponse(dumps({
"success": True,
"pages": [{"id": page.id, "title": page.title, "url": page.image} for page in Page.objects.filter(site = site)]
}))
According to Firebug, server send right ids in data, but console.log(..) instead of correct id (4040956363970588323), outputs id 4040956363970588000.
Why does this happen?
Without right ids, any chance, that my wizard will work correctly :)
My guess is something is going wrong in the conversion to JSON. When you write the value, you'll probably need to put quotes around it, to make sure it's treated as a string.
That looks like some kind of overflow problem to me.
According to this discussion here on SO, JavaScript can only handle INTs of size 2^64, which means the max INT is somewhere around
184467440737100000
which is much less than
4040956363970588323
EDIT: Sorry, the largest exact integer is 2^53, but the case is the same.

Categories