3

How to send multiple parameters in an angularjs $http.post to web api controller action method.

Below is my code.

AngularJS code

var complexObj = { prop1: "value", prop2: "value" };

var id = 100;

var data = { id: id, complexObj: complexObj };

$http({
       method: 'POST',
       url: 'http://localhost/api/WebApiController/MethodName',
       data: data
       }).success(function (data, status) {
                //do something...
            });


$http.post('http://localhost/api/WebApiController/MethodName', data)
     .success(function (data, status) {
                     //do something...
                 });

Web API controller

[RoutePrefix("api/WebApiController")]
public class WebApiController: ApiController
{
    [Route("MethodName")]
    public ReturnValue WebApiAction(string id,ComplexObj complexObj)
    {
        // process request and return data...
    }
}

I am getting below response message in fiddler.

{ "message": "No HTTP resource was found that matches the request URI 'http://localhost/api/WebApiController/MethodName'.",
"messageDetail": "No action was found on the controller 'WebApiController' that matches the request." }

When I send the complexObj alone, its hitting the web api,but all properties are null or set to default values.

What am I doing wrong? How can I send two or more parameters(both complex objects and string/int) in $http.post? Any help is much appreciated.

5
  • Have you tried serializing the object (JSON.stringify(...)) Commented Feb 3, 2016 at 16:32
  • @ItaloAyres yes, its not working. Commented Feb 3, 2016 at 16:34
  • What's the definition of ComplexObj? Also, what happens when you set var id = '100'; Commented Feb 3, 2016 at 16:36
  • I know that in Spring, we can use @RequestBody to post a JSON object. If you are using another framework, you can try to use something similar. Commented Feb 3, 2016 at 16:37
  • @Josh 'id' is just an another parameter, i need to pass to web api. Commented Feb 3, 2016 at 17:06

1 Answer 1

3

Web API doesn't support multiple post parameters in this way.

Your best bet is to roll up Id into ComplexObj and post it as a single parameter.

complexObj.id = id;
var data = complexObj;

Update your signature to take just a single object.

[Route("MethodName")]
public ReturnValue WebApiAction(ComplexObj complexObj)
{
    // process request and return data...
}

If you absolutely want to be able to post data like this, consider Rick Strahl's post on creating a custom parameter binder.

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

1 Comment

Rick Strahl's solution only supports simple types. To support complex objects, check out MultiPostParameterBinding

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.