3

I used .NET 7.x (ASP.NET Core 7 MVC) and JavaScript Library v1.10.2 and use XHR in Ajax to get data from the controller as shown here.

Send a request to get data like this:

function SendRequestToGetData() {
   var xhr = $.ajax({
     url: "/Line/GetData",
     type: 'POST',
     dataType: 'json',
     contentType: 'application/json; charset=utf-8',
     success: function (msg) {

        // Here I can get the property with this: 
        var sentdata = msg.Name;
      },
      error: function (xhr) {}
   });
 }

On the server side in the controller init an object and return it like this:

public class TestObject
{
    public string Name { get; set; }
}

//------------------------------------------------

public class LineController : Controller
{
    [HttpPost]
    public JsonResult GetData()
    {
        TestObject testbject=new TestObject {Name="xxxxxxx"};
        return Json(testbject);
    }
}

It works fine and OK. I updated my project to .NET 8 (.NET Core MVC) and updated JavaScript to Library v3.7.1. Now old codes don't work until the first letter of the property to lowercase so that the codes work correctly.

It means to change this:

var sentdata=msg.Name;

to this:

 var sentdata=msg.name; //with the lowercase

Until it works, want to know what and why caused this?

0

1 Answer 1

2

This behaviour depend on JS Library version, but not .NET version. According your description the old version JS Library is using the JSON Serializer convertor with default property naming policy set to JsonNamingPolicy.PascalCase. But in the JS Library v3.7.1 the default property naming policy is set to JsonNamingPolicy.CamelCase.

To override the default property naming policy used by the JSON Serializer convertor create the JsonSerializerOptions() object and pass it in the second parameter of the Json() object.

The created JsonSerializerOptions object without parameters will contain the PropertyNamingPolicy property set to null and the JSON Serializer convertor will use JsonNamingPolicy.PascalCase property naming policy.

[HttpPost]
public JsonResult GetData()
{
    var testobject = new TestObject { Name="some-text"};
    return Json(testobject, new System.Text.Json.JsonSerializerOptions());
}

For an additional information see How to customize property names and values with System.Text.Json

Not the answer you're looking for? Browse other questions tagged or ask your own question.