How to solve Invalid JSON primitive issue in ASP.NET?

This post can help you to solve “Invalid JSON primitive: {any-value}” issue when you make a web request from browser to the server.

I can make an assumption that you are either using jQuery or AngularJS light version of jQuery (or some other way) to make an AJAX request from your client to the server. In any of the above case, your could may look similar to the code snippet below.

Based on the code above, jQuery might not send it as JSON data but instead serialise it to “foo=foovalue&bar=barvalue” thus you get the error “Invalid JSON primitive: foo”.  The code has “contentType” set to “application/json” which means that the data send to the server will follow the JSON format but what is actually sent is a plain JavaScript object which gets serialised as percentile-encoded-string by jQuery.

Just a reminder that – “contentType” is the type of data you are sending to the server. Also, if you don’t set any “contentType” for the ajax method, the default one that jQuery uses is “application/x-www-form-urlencoded; charset=UTF-8”. So, make sure you set the correct type when interacting with the server.

And “dataType” is the format what you are expecting to get back from the server. e.g. json, html, text, etc.

The correct way:

To fulfil our promise, we need to send the data as JSON format. For which we can use the “JSON.stringify” method to wrap the data as string as shown below. The JSON object has a good browser support.

Now, ASP.NET will be able to parse the data for you.

 

Siddharth Pandey

Siddharth Pandey is a Software Engineer with thorough hands-on commercial experience & exposure to building enterprise applications using Agile methodologies. Siddharth specializes in building, managing on-premise, cloud based real-time standard, single page web applications (SPAs). He has successfully delivered applications in health-care, finance, insurance, e-commerce sectors for major brands in the UK. Other than programming, he also has experience of managing teams, trainer, actively contributing to the IT community by sharing his knowledge using Stack Overflow, personal website & video tutorials.

You may also like...

Advertisment ad adsense adlogger