3

I am trying to send a stringified JSON object to MVC method via the following jQuery Ajax call:

$.ajax({
           type: "POST",
           url: "UpdateItem",
           contentType: "application/json; charset=utf-8",
           dataType: "json",
           processData : false,
           data:
               {
                    item: JSON.stringify(_item)
               },
           success: function (data) {
               alert(data);
           },
           error: function (x, t, m, b) {
               DisplayErrorMessage(x.responseText);
           }
       });

and the stringified version of my data is as follows:

{
    "Id": 4,
    "ParentId": 1,
    "TypeId": 2,
    "TypeText": "Solid",
    "ItemNo": 8,
    "StandartTypeId": 7,
    "StandartTypeText": "Dept",
    "GradeTypeId": 6,
    "GradeTypeText": null,
    "Thickness": 0.044,
    "ThicknessToleranceId": 1,
    "ThicknessToleranceText": null,
    "Width": 42,
    "MinWeightId": 6,
    "MinWeight": null,
    "MinWeight2": null,
    "MaxWeightId": 8,
    "MaxWeight1": null,
    "MaxWeight2": null,
    "DefId": null,
    "Quantity": 330690,
    "QuantityToleranceId": 3,
    "QuantityToleranceText": "",
    "ProductionDate": "2014-11-05T22:00:00.000Z",
    "PortId": 3,
    "PortText": null,
    "DeliveryDate": "2014-10-08T21:00:00.000Z",
    "MaterialTypeId": 2,
    "MaterialTypeText": "",
    "FeePrepaid": 30,
    "Price": 525,
    "Extra1": 0,
    "Extra1": 0,
    "CurrencyId": 2,
    "CurrencyText": "",
    "StatusId": 2,
    "StatusText": "",
    "ReasonId": null,
    "ReasonText": null,
    "Note": "New note",
    "CreateDate": "2014-11-06T09:12:29.661Z",
    "CreateUserId": 0,
    "CreateUserText": "",
    "CancelDate": null,
    "CancelUserId": null,
    "CancelUserText": null,
    "ChemicalProperties": null,
    "TechnicalProperties": null,
    "Remarks": null
}

I have successfully validated my JSON object via http://jsonlint.com/.

I try to get the response into the following method :

public JsonResult UpdateItem(string json)
{
    var js = new JavaScriptSerializer();
    var deserializedItem = (object[])js.DeserializeObject(json);


    return Json(null);
}

But when I try to post via Ajax I get the following error Message before ASP.NET MVC Controller method call:

Invalid JSON primitive: object. Exception Details: System.ArgumentException: Invalid JSON primitive: object.

And my Stack Trace is as follows:

[ArgumentException: Invalid JSON primitive: object.]
System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializePrimitiveObject() +915
System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth) +597
System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeList(Int32 depth) +354
System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth) +531
System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String input, Int32 depthLimit, JavaScriptSerializer serializer) +108
System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit) +210
System.Web.Script.Serialization.JavaScriptSerializer.DeserializeObject(String input) +86
System.Web.Mvc.JsonValueProviderFactory.GetDeserializedObject(ControllerContext controllerContext) +191
System.Web.Mvc.JsonValueProviderFactory.GetValueProvider(ControllerContext controllerContext) +19
System.Web.Mvc.<>c__DisplayClassc.<GetValueProvider>b__7(ValueProviderFactory factory) +34
System.Linq.WhereSelectEnumerableIterator`2.MoveNext() +145
System.Linq.WhereSelectEnumerableIterator`2.MoveNext() +171
System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) +460
System.Linq.Enumerable.ToList(IEnumerable`1 source) +58
System.Web.Mvc.ValueProviderFactoryCollection.GetValueProvider(ControllerContext controllerContext) +281
System.Web.Mvc.ControllerBase.get_ValueProvider() +40
System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor) +60
System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor) +117
System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__1e(AsyncCallback asyncCallback, Object asyncState) +446
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction(ControllerContext controllerContext, String actionName, AsyncCallback callback, Object state) +302
System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__17(AsyncCallback asyncCallback, Object asyncState) +30
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state) +382
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +317
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +15
System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__2(AsyncCallback asyncCallback, Object asyncState) +71
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +249
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +50
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +16
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +301
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

3 Answers 3

5

Did you try with :

data: JSON.stringify(_item)

Just a guess but I think using:

data:
           {
                item: JSON.stringify(_item)
           }

won't get you what you want.

Since you're waiting for a String in the controller, a String should be passed in the request.

If you want multiple objects you'll have to make a variable that will convert to something like :

JSON.stringify(_items) => "[{id:1},{id:2}]";

And then use it in : data: JSON.stringify(_item)

Sign up to request clarification or add additional context in comments.

9 Comments

When I do that it falls to ASP.NET MVC Controller method "UpdateItem", but this time the parameter "json" is null.
Also the question is a simplified of the real-world scenario. In fact I have to send multipler objects at once. So, I should better use "data: {}" structure.
Well in this case you'll have to send an array of object in JSON format to data, not a list of data. You shouldn't have null anyway, can you try with this simple data : JSON.stringify({id: 20}) to be sure the problem is not in your stringified value
I don't know what is wrong, but even "data: [JSON.stringify({ id: 20 }), JSON.stringify({ id: 30 })]," says "Invalid JSON primitive: {"id":30}. "
Did you try with just data: JSON.stringify({id: 20}) ? No [ anywhere.
|
0

Setting the "traditional" property of the Ajax request to true would suffice.

And also as Michael suggests, instead of multiple values, only single parameter should be set as follows:

The final Ajax call should be:

$.ajax({
       type: "POST",
       url: "UpdateItem",
       contentType: "application/json; charset=utf-8",
       dataType: "json",
       traditional: true,
       processData : false,
       data: JSON.stringify(_item),
       success: function (data) {
           alert(data);
       },
       error: function (x, t, m, b) {
           DisplayErrorMessage(x.responseText);
       }
   });

5 Comments

Setting traditional to true isn't IMHO the good solution. Reading api.jquery.com/jQuery.param it seems you won't be able to have nester objects.
On the contrary my real-world object is an object which has regular types as properties and three (other object) collections as properties. IT seems to work OK if I understand "nester" correctly.
From the doc: With traditional=false ==> foo[1][]=3&foo[1][]=4&foo[2]=2&foo[3]=3&bar=42 With traditional=true ==> foo=[object Object]&bar=42
Yes, but I am setting the traditional proprty as true, not false.
That's the problem, a nested object (object contained by another object) won't be converted to JSON but simply shown as "[object Object]"
0

Just run with my code In my reactjs

$.ajax({
            type: 'POST',
            url: 'http://example.com/ExampleService/ExampleMethod',
            //data: JSON.stringify({transferData: objImages}), => Wrong
            //data: { transferData: JSON.stringify(objImages) }, => Wrong
            //data: JSON.stringify(objImages), => Wrong
            data: JSON.stringify({ 'transferData': JSON.stringify(objImages) }), // transferData is name
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            success: function (data) {
                alert(data);
            },
            failure: function (errMsg) {
                alert(errMsg);
            }
        });

In asp.net mvc webservice

public ActionResult ExampleMethod(string transferData)
    {
        //dynamic transferObj = JsonConvert.DeserializeObject(transferData);
        //return Json(transferObj);

        return Json(transferData);
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.