Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AJAX Passing multiple parameter to WebApi

AJAX request:

$.ajax({
            url: url,
            dataType: 'json',
            type: 'Post',
            data: {token:"4", feed:{"id":0,"message":"Hello World","userId":4} }
        });

Server Side Web API:

 [HttpPost]
 public HttpResponseMessage Post(string token, Feed feed)
 {
    /* Some code */

    return new HttpResponseMessage(HttpStatusCode.Created);
 }

Error Code 404: {"message":"No HTTP resource was found that matches the request URI 'localhost:8080/api/feed'.","messageDetail":"No action was found on the controller 'Feed' that matches the request."}

Why I am getting this error and Why I am not able POST multiple parameters to my API?

like image 281
Mohsin JK Avatar asked Sep 22 '13 16:09

Mohsin JK


1 Answers

Start by writing a view model:

public class MyViewModel
{
    public string Token { get; set; }
    public Feed Feed { get; set; }
}

that your controller action will take as parameter:

[HttpPost]
public HttpResponseMessage Post(MyViewModel model)
{
    /* Some code */

    return new HttpResponseMessage(HttpStatusCode.Created);
}

and finally adapt your jQuery call to send it as JSON:

$.ajax({
    url: url,
    type: 'POST',
    contentType: 'application/json',
    data: JSON.stringify({
        token: '4',
        feed: {
            id: 0,
            message: 'Hello World',
            userId: 4
        } 
    })
});

Important things to note for the AJAX call:

  • setting the request contentType to application/json
  • wrapping the data in a JSON.stringify function to effectively convert the javascript object to a JSON string
  • removed the useless dataType: 'json' parameter. jQuery will automatically use the Content-Type response header sent by the server to deduce how to parse the result passed to the success callback.
like image 107
Darin Dimitrov Avatar answered Nov 15 '22 01:11

Darin Dimitrov