Home > Software design >  Incorrect encoding of contentType in AJAX Call for MVC Action
Incorrect encoding of contentType in AJAX Call for MVC Action

Time:04-01

I am trying to call an AJAX function to transfer some JSON data (Roughly 38Kb in size) which will be cast onto a List<ModelClass> in the Controller Action for other processors.

(Simplified) _oRecords Data Format before AJAX transfer - console.log(JSON.stringify(_oRecords));

[{{"sn":2208,"timeStampMarker":"","Id":0,"Data1":1,"Data2":2,"Data3":3},{"sn":2209,"timeStampMarker":"","Id":0,"Data1":1,"Data2":2,"Data3":3},{"sn":2210,"timeStampMarker":"","Id":0,"Data1":1,"Data2":2,"Data3":3},}]

(Simplified) Data Format on Controller Action - F12 Network Payload

records=[{"sn":2208,"timeStampMarker":"","Id":0,"Data1":1,-ata2":2,"Data3":3},{" sn":2159,"timeStampMarker":"","Id":0,"Data1":1,-ata2":2,"Data3":3},{" sn":2159,"timeStampMarker":"","Id":0,"Data1":1,-ata2":2,"Data3":3},{"

Essentially, the special characters such as '[', '{', ',' are encoded wrongly by contentType option of the AJAX call. Following this post, the above result was received after configuring the AJAX call as below:

Ajax Call COnfiguration - View

$.ajax({
    url: '../CSV/SaveDataFoo/',
    type: "POST",
    cache: false,
    contentType: "application/json; charset=utf-8",
    data: { records: JSON.stringify(_oRecords) },
    dataType: "json"
});

Controller

public JsonResult SaveDataFoo(List<DataModelClass> records)
{
     //Does some things with `records` List<T>

     return Json(null);
}

Due to the incorrect transfer, records's Count is [0] (as expected). Is there any other AJAX configuration or perhaps further manipulation of _oRecords I can do to fix this? Thanks in advance!

CodePudding user response:

Two things here...

  1. To send a JSON request body with jQuery, don't nest the data in an object. jQuery will treat that as application/x-www-form-urlencoded

    $.ajax({
      url: "../CSV/SaveDataFoo/",
      method: "POST",
      contentType: "application/json",
      processData: false,
      data: JSON.stringify(_oRecords),
      dataType: "json"
    });
    
  2. To tell your controller action to parse the data out of the response body, use the [FromBody] attribute

    public JsonResult SaveDataFoo([FromBody] List<DataModelClass> records)
    
  • Related