AdrianD AdrianD - 4 months ago 20
JSON Question

WebAPI/MVC - sending json list to server

I am having a problem sending 2 particular objects to the server.


  1. I have a form with an input and a text area




    Send


    function SendServer()
    {
    $.ajax({

    url: '/api/Service',
    type: "POST",
    contentType: 'application/json',
    data: {} //!!!
    success: function (response) {
    },

    error: function (er) {
    }
    });


    }



the issue is that my text area will contain an user input json of the form:

{
"list": [
{
"name": "john smith",
"lastaccess": "2016-01-01T07:21:31 -00:00"
},
{
"name": "paul marley",
"lastaccess": "2016-01-01T07:22:31 -00:00"
}
]
}


I need to send both values to the server:

public class ServiceController : ApiController
{
public string Post( *something* )
{}
}


I can reach the server, but I donno how to properly send the 2 objects so I can retrieve them on the server?

I have been trying a lot of options, nothing worked :(

Answer

Since you are sending a json which user enters using a form, you might consider using JObject class as your web api method parameter.

So in your form

<form id="form1">
    <input type="text" id="val1" name="val1" value="1" />
    <textarea class="form-control" id="json" name="json"></textarea>
    <button id="send">Send</button>
</form>

Now, on the button click,read the values of both the inputs and create a new object, and send that to the server.

$(function () {
    $("#send").click(function (e) {
        e.preventDefault();

        var v = $("#val1").val();
        var t = $("#json").val();
        var d = { val1: v, json: t };
        $.ajax({

            url: '/api/values',
            type: "POST",
            contentType: 'application/json',
            data: JSON.stringify(d),
            success: function (response) {
                console.log(response);
            },

            error: function (er) {
                console.log(er);
            }
        });

    });
});

And in the WebApi endpoint, you may use JObject as the parameter. The default model binder will be able to map the posted values to an object of JObject.

    public HttpResponseMessage Post([FromBody]JObject value)
    {
        var v = value["val1"];
        var j = value["json"];
        // do something with these 
        // v.Value will give you the value
        return Request.CreateResponse("Something received");
    }

JObject class belongs to Newtonsoft.Json.Linq namespace. So make sure to have a using statement to include that in your web api controller.