Sending JSON to a POST method inside a Controller

Author:Ben Schulz
Last Updated:November 07, 2022 5:30 PM

POST requests to a controller with JSON data can be easily implemented if the controller is already configured (see the “Integrating .NET Controllers With Titan” article). This guide assumes a basic familiarity with that process.

The front end JavaScript needs to follow this general format to be usable by the controller:

let rawData = '{ "property1": "first", "property2": "second" }';
let jsonData = JSON.stringify(rawData);

$.ajax({
    type: "POST",
    url: "/ControllerClass/PostMethod",
    data: { "parameter": jsonData },
    contentType: "application/json"
});

Make sure that the url field is using the appropriate path ([Controller Name]/[Method Name]). The controller guide mentioned above details how this path is defined via route attributes. In the controller, you will need to define a separate class that matches the posted JSON. This allows the JSON to automatically be deserialized by the POST method. To accept the JSON string above, the deserialization class would need to be defined like this:

public class jsonContent
{
     public string property1 { get; set; }
     public string property2 { get; set; }
}

In order to work, the names of this class’s properties must exactly match the incoming JSON keys. Once this class is defined, you can write the POST method itself:

[Route("PostMethod")]
[HttpPost]
public string PostMethod(jsonContent parameter)
{
     string first = parameter.property1;
     string second = parameter.property2;

     return first + " " + second;
}

Once this method is hit, "parameter" will be a jsonContent object “filled in” with the JSON sent from the front end. Using the JSON above, parameter.property1 would be set to “first” and parameter.property2 would be set to “second”. Therefore, PostMethod would return the string “first second” back to the front end.

top