1

Can't figure out this simple ajax call. The controller successfully returns the json file as it should, but is logging two zeroes as the values for both the country and amount, which are incorrect. What am I doing wrong here?

controller:

[HttpPost("search")]
public IActionResult test(int country, int amount)
{
    System.Console.WriteLine(country);
    System.Console.WriteLine(amount);
    return Json("success : true");
}

jQuery:

var data = "{ 'country': 2, 'amount': 4}";

$.ajax({
    url: "search",
    type: "POST",
    data: data,
    cache: false,
    contentType: "application/json",
    success: function (data) {
        alert("hi"+ data);
    }
});
Kirk Larkin
  • 84,915
  • 16
  • 214
  • 203

4 Answers4

3

Create a model to hold the desired values

public class TestModel {
    public int country { get; set; }
    public decimal amount { get; set; }
}

Update the action to expect the data in the body of the request using [FromBody] attribute

[HttpPost("search")]
public IActionResult test([FromBody]TestModel model) {
    if(ModelState.IsValid) {
        var country = model.country;
        var amount = model.amount;
        System.Console.WriteLine(country);
        System.Console.WriteLine(amount);
        return Ok( new { success = true });
    }
    return BadRequest(ModelState);
}

Client side you need to make sure the data is being sent in the correct format

var data = { country: 2, amount: 4.02 };

$.ajax({
    url: "search",
    type: "POST",
    dataType: 'json',
    data: JSON.stringify(data),
    cache: false,
    contentType: "application/json",
    success: function (data) {
        alert("hi"+ data);
    }
});

Reference Model Binding in ASP.NET Core

Nkosi
  • 235,767
  • 35
  • 427
  • 472
2
  1. You should use JSON.stringify to convert a object into a json string. Do not try to use string concatenation to do this.
  2. Your types for amount do not match what you are sending. A money type should probably be decimal in c#.
  3. Return an anonymous object from the c# method as well and pass that to Json.
  4. The content-type is incorrect, see also What is the correct JSON content type?
[HttpPost("search")]
public IActionResult test(int country, decimal amount)
{
    System.Console.WriteLine(country);
    System.Console.WriteLine(amount);
    // return an anymous object instead of a string
    return Json(new {Success = true});
}

jQuery:

var data = JSON.stringify({country: 2, amount: 4.02});

$.ajax({
    url: "search",
    type: "POST",
    dataType: 'json',
    data: data,
    cache: false,
    contentType: "application/json",
    success: function (data) {
        alert("hi"+ data);
    }
});
Igor
  • 60,821
  • 10
  • 100
  • 175
1

What am I doing wrong here?

dataType is not required so you can omit that.

4.02 is not an int so you should probably replace that with decimal

and contentType should be application/json

Erik Philips
  • 53,428
  • 11
  • 128
  • 150
  • Corrected my json: "{ country: 2, amount: 4}", removed dataType and truncated the decimal. All with no luck, still zeros :| – Thomas Baldwin Dec 04 '18 at 22:03
0

Thanks everyone! Got it working with your help.

It won't work after I remove [FromBody]

 [HttpPost("search")]
        public IActionResult test([FromBody] string data)
        {
            System.Console.WriteLine(data);
            return Json(new {Success = true});
        }

jQuery:

var data = JSON.stringify("{ 'data': 'THOMAS' }");

    $.ajax({
        url: "search",
        type: "POST",
        data: data,
        cache: false,
        contentType: "application/json",
        success: function (data) {
            alert("hi"+ data);
        }
    });