Home > front end >  C# JObject arrives to the front as an empty list
C# JObject arrives to the front as an empty list

Time:11-20

I'm using jQuery Ajax to send a Newtonsoft object from a MVC controller task to the front, but I have been struggling a lot with it. For some reason the object arrives as an empty list I tried to simplify the object thinking that the problem was the structure nesting other objects, but it doesn't work even in the most simple case. I updated the version of Newtonsoft as said in this other question Nested JObjects getting serialized as empty arrays but my problem persist. I know it looks easy but I'm not sure what I may be doing wrong. Here is the method in the controller

[HttpPost]
public async Task<JsonResult> Something(string data)
{
            //some asynchronous stuff
            var jsonObject = new JObject();
            jsonObject.Add("x", "text");
            return Json(jsonObject);
}

My JQuery ajax call

 $.ajax({
            type: "POST",
            url: url,
            data: JSON.stringify(parameters),
            contentType: "application/json",
            success: function (data) {
               debugger;
            }
        }).fail(function (jqXHR, textStatus, errorThrown) {          
});

And the answer arrives as somethign like this

[[[]]]

I'm going crazy with this problem any suggestions are really apreciated

CodePudding user response:

I can' t see any async in your code, but in any case try this

public async Task<ActionResult> Something()
{
     return Ok( new { x="text"} );
}

CodePudding user response:

I add an aswer to my own question hoping that it may help someone else in the same situation. I wrapped the answer in the following manner and now it works fine. I'm not sure why it's not possible to send it directly but maybe is related to a problem on the nested objects.

JsonResult data = new JsonResult();
        data.Data = new
        {
            success = true,
            result = JsonConvert.SerializeObject(rta.Data)
        };

Also may be useful to be careful with the maxlength of the strings because that may add more problems if the original object is too big.

  • Related