Home > Enterprise >  JSON object model not utilizing JsonProperty names
JSON object model not utilizing JsonProperty names

Time:11-10

How do I get the component factory to bind and resolve to the JSON property attribute names, in an AJAX request to Razor action result? Right now, I have a workaround where I just send the JSON string and deserialize it server-side, but thinking there must be a way for the action to do this.

For example, I have the following model:

public class ExampleClass 
{
    [JsonProperty("@first-name")]
    public string FirstName { get; set; }

    [JsonProperty("@last-name")]
    public string LastName { get; set; }
}

I then try to send my model using the following script (note I have removed the double '@@' for razor view model binding to avoid confusion). This is the "rendered" script:

var model = {
        "@first-name": "test",
        "@last-name": "test"
    };

    $.ajax({
        url: '/Dashboard?handler=test',
        type: "POST",
        contentType: "application/json",
        data: JSON.stringify(model),
        beforeSend: function (xhr) {
            xhr.setRequestHeader("RequestVerificationToken", $('input:hidden[name="__RequestVerificationToken"]').val());
        },
        success: function (result) {

        },
        error: function (result) {
        }
    });

On my handler, I then get a null object (model values are null)

public IActionResult OnPostTest([FromBody] ExampleClass model)

If I change the model to the following, everything works fine:

var model = {
        "FirstName": "test",
        "LastName": "test"
    };

I can see the object is getting passed correctly enter image description here

CodePudding user response:

All this code was tested in Visual Studio and working properly.

You made a bug, you added an extra @ (I don't know why you were doing it)

var model = {
        "@@first-name": "test",
        "@@last-name": "test"
    };

if you use

var model = {
        "@first-name": "test",
        "@last-name": "test"
    };

everything works properly

as well you can change property attributes, instead of json, it works properly too

public class ExampleClass 
{
    [JsonProperty("@@first-name")]
    public string FirstName { get; set; }

    [JsonProperty("@@last-name")]
    public string LastName { get; set; }
}

CodePudding user response:

I made a silly mistake... I was using Newtonsoft.Json library attribute property binding (JsonProperty), instead of the serializer factory being used by the action (JsonPropertyName) in System.Text.Json.Serialization... very silly moment. Realized once I removed the Newtonsoft import and saw my class now had errors,

Now working...

public class ExampleClass 
{
    [JsonPropertyName("@first-name")]
    public int FirstName { get; set; }

    [JsonPropertyName("@last-name")]
    public int LastName { get; set; }
}
  • Related