joecoder
joecoder

Reputation: 93

POST JSON array data with parameters in Web API

UPDATED:

I am creating a simple app using MVC and Web API as an exercise which is new to me. It lets user paste a JSON data array into a textarea and pass it on to a Web API controller via AJAX with a sort parameter where value is based on the chosen option in the dropdown. The API controller will perform the sorting. Once sorted, it will return the URL containing the parameter value similar to one's below:

Home/Index/?sort=age
Home/Index/?sort=lastName
Home/Index/?sort=registered

I am not certain where to put the query string parameter.

enter image description here

UPDATED:

Here's my AJAX call so far..

$(document).ready(function () {
    var profiles = $('#txtJSONData').val().replace(/(\r\n|\n|\r)/g,"");
    $('#btnSubmit').click(function () {
        $.ajax({
            url: '/api/default',
            data: JSON.stringify(JSON.parse(profiles)),
            type: 'POST',
            dataType: 'application/json',
            success: function(data) {
                alert("success");
            },
            error: function() {
                alert("error");
            }
        });
    });
});

UPDATED:

I am already getting the values of the JSON array being posted. However, I also need to pass in the sort query string parameter and its value to perform the sorting. I am not sure where to put it. Do I need to append it on the API route? Or let MVC controller handle it?

public class DefaultController : ApiController
{
    [Route("api/default")]
    [HttpPost]
    public HttpResponseMessage Post([FromBody] JToken jsonBody)
    {

    }
 }

Been trying to search for a solution both here and over the web but couldn't find a similar scenario with mine. Any help and/or suggestions will be highly appreciated. Thanks in advance!

Upvotes: 0

Views: 2442

Answers (1)

Efe Kaptan
Efe Kaptan

Reputation: 465

1 - Add sort parameter to your action

public class DefaultController : ApiController
{
    [Route("api/default")]
    [HttpPost]
    public HttpResponseMessage Post(string sort, [FromBody] JToken jsonBody)
    {

    }
 }

2 - You can call your action like below:

$(document).ready(function () {
    var profiles = $('#txtJSONData').val().replace(/(\r\n|\n|\r)/g,"");
    $('#btnSubmit').click(function () {
        $.ajax({
            url: '/api/default?sort=asc',
            data: JSON.stringify(JSON.parse(profiles)),
            type: 'POST',
            dataType: 'application/json',
            success: function(data) {
                alert("success");
            },
            error: function() {
                alert("error");
            }
        });
    });
});

Upvotes: 1

Related Questions