简体   繁体   中英

get data from ajax with POST

right now I am stuck on a problem. I guess it is a very basic thing. But after doing researches for hours it would be great if someone can give me a quick advice. So I am trying to call my PUT method from my api (C#)

    [HttpPost]
    public String Post(String id)
    {

        return id;
    }

It is called when i press a button. The button function is this:

<script>
function sendData() {
    $.ajax({
        url: '/api/values',
        type: 'POST',
        data: {'id':"100014"},
        dataType: 'json',
        contentType: 'application/json',
    });
}

If I call the GET method everything works fine. But trying to call the POST method it only returns that the resource is not supported for HTTP Post. I tested the method with Postman. Here the Post method works. But I do not want to pass these data into the Url but into the data from Ajax.

It would be great if someone can help me out.

EDIT: I just tried some stuff. My final result is this:

        [HttpPost]
    public async Task<IHttpActionResult> Post(int id)
    {
        var rawMessage = await Request.Content.ReadAsStringAsync();
        return Ok(rawMessage);
    }

It worked out for me fine.

Problem is that you route is not found. Try

     [HttpPost]
     [Route("getValues")]
public String Post(String id)
{

        return id;
    }

You can even add before controller class:

[RoutePrefix("api/values")]

and then call it with

url: '/api/values/getValues',

Please check if you referenced the correct library.

If you're using System.Web.Mvc this issue might occur. Trying removing that and referencing System.Web.Http instead.

Hope this solves your issue.

You should wrap your output with Ok() method . Something like

Use your returm type as IHttpActionResult

 [HttpPost]
    public IHttpActionResult Post(String id)
    {

        return Ok(id);
    }

You should convert a JavaScript object to a string with JSON.stringify(). You can modify your method in script like this.

<script>
function sendData() {
var obj = { id:'100014'};
    $.ajax({
        url: '/api/values',
        type: 'POST',
        data: JSON.stringify(obj),
        dataType: 'json',
        contentType: 'application/json',
        success: function(data) {
            alert(data);
        }
    });
}
</script>

By the way, I see your path is incorrect. It should be /api/post

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM