My server is using ServiceStack and would like to receive some data like this:
{
Customer: {
Company: \"TheCompany\",
RegionCode: \"AU_NS
While Mythz suggestion of posting JSV values would work, it can sometimes be cumbersome to build and maintain complex JSV in JavaScript. For example, you may have to deal with escaping user inputted data, and syntax issues can be hard to track
This solution looks complex but it's really not, and is highly re-usable and only requires that you can send encoded JSON, which from jQuery is very easy.
JSON.stringify(data)
Data
fieldData
field into your DTOMy solution sends the DTO object encoded as JSON in a form post to the service. Then a simple filter intercepts the request and populates the DTO from the JSON payload.
public class GetFromJsonVariableAttribute : Attribute, IHasRequestFilter
{
string _variableName;
public GetFromJsonVariableAttribute(string variableName = "Data")
{
_variableName = variableName;
}
public void RequestFilter(IRequest req, IResponse res, object requestDto)
{
// Convert the JSON payload to DTO format
var payload = req.GetParam(_variableName);
if(payload != null)
requestDto = JsonSerializer.DeserializeFromString(payload, requestDto.GetType());
}
public int Priority { get { return int.MinValue; } }
IHasRequestFilter IHasRequestFilter.Copy() { return this; }
}
Then to use you simply add the attribute to your DTO. Data
is the name of the form variable that will hold the JSON payload. You can choose any name you want here.
[GetFromJsonVariable("Data")]
[Route("/Customers","POST")]
public class CreateCustomerRequest : IReturnVoid
{
public Customer Customer { get; set; }
public Name Name { get; set; }
}
$("#CreateCustomer").on("submit", function(){
// Get the form values into simple key value array
var values = {};
$.each($(this).serializeArray(), function(){ values[this.name] = this.value; });
// Prepare the DTO
var data = {
Customer: {
Company: values["Company"],
RegionCode: values["RegionCode"]
},
Name: {
First: values["First"],
Last: values["Last"]
}
};
// Convert it to JSON
$('#PayloadForm [name="Data"]').val(JSON.stringify(data));
$('#PayloadForm').submit();
return false;
});
With the HTML create the form your user will interact with, with no action, but is linked to the jQuery submit event code; And a hidden form that will actually perform the synchronous POST. Note the attribute Data
matches that of the attribute the payload should be received on