How do I send a complex JSON object from an HTML form using SYNCHRONOUS page POST?

后端 未结 4 2067
清歌不尽
清歌不尽 2021-01-15 11:21

My server is using ServiceStack and would like to receive some data like this:

{
    Customer: {
        Company: \"TheCompany\",
        RegionCode: \"AU_NS         


        
4条回答
  •  囚心锁ツ
    2021-01-15 11:49

    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.

    Full Demo Source Code Here

    Process - How it works:

    1. Your jQuery creates the DTO using the form data on submit
    2. The DTO is encoded as JSON, simply using JSON.stringify(data)
    3. The JSON is sent in a hidden form as the value of Data field
    4. A server DTO attribute filter deserializes the JSON value of Data field into your DTO
    5. Your service see the DTO populated as normal.

    Filter Attribute:

    My 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; }
    }
    

    Usage

    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; }
    }
    

    Client Side (jQuery):

    1. Get your form values
    2. Build the required DTO structure as a JavaScript object
    3. Convert that DTO to a JSON string
    4. Set your hidden form value to the DTO string & submit
    $("#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





提交回复
热议问题