2

My AJAX is not sending data to my http post controller.

My controller:

[Route("api/sendingData")]
public class TestController : ApiController
{
    [HttpPost]
    public string Post([FromBody] int propertyID)
    {
        return string.Format("Test");
    }
}

My AJAX:

$.ajax(
    {
        url: "api/sendingData",
        type: "POST",
        dataType: 'json',
        data: {
            'propertyID': '1'
        },
        success: function (result) {
            console.debug(result);
            alert(result);
        },
        error: function (xhr, status, p3, p4) {
            console.debug(xhr);
            var err = "Error " + " " + status + " " + p3;
            if (xhr.responseText && xhr.responseText[0] == "{")
                err = JSON.parse(xhr.responseText).message;
            alert(err);
        }
    });

I'm trying to send the propertyID=1. However, when I debug my controller, it shows propertyID=0.

Does anyone know what is wrong?

6
  • Please test this: data: { propertyID: JSON.stringify('1')} Commented Oct 31, 2017 at 20:30
  • Thanks. But still the same problem Commented Oct 31, 2017 at 20:32
  • Try it by removing the single quotes : data: {propertyID: 1 }, Commented Oct 31, 2017 at 20:35
  • Solution: data : { "" : 1 }. I don't know why Commented Oct 31, 2017 at 20:38
  • Also, the [FromBody] could be the problem. What happens if you remove it or use [FromUri] instead? Commented Oct 31, 2017 at 20:39

1 Answer 1

2

Might look weird but you're only sending one value, not a model, so the stringify is JSON.stringify(value)

var propertyID = 1;
$.ajax({
    url: "api/sendingData",
    contentType: 'application/json',
    type: 'POST',
    data: JSON.stringify(propertyID),
    success: function (result) {
        console.debug(result);
        alert(result);
    },
    error: function (xhr, status, p3, p4) {
        console.debug(xhr);
        var err = "Error " + " " + status + " " + p3;
        if (xhr.responseText && xhr.responseText[0] == "{")
            err = JSON.parse(xhr.responseText).message;
        alert(err);
    }
});

Also I have removed dataType json because your action method is not returning json but a string. Now I'm getting success.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.