Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass two parameters to WEB API call using angular post

I have the following post method in my WEB API controller:

public async Task<HttpResponseMessage> SendPost(Application application)

I call it through javascript using angular.js $http.post and pass through the application parameter as JSON:

$http.post("/api/AController/SendPost", JSON.stringify(application)).
            success(function (data, status, headers, config) {
}

This works.

Now I want to pass through a second parameter as a simple string (I can't modify the existing application JSON object).I tried a few different ways suggested on the web but none of them seem to work. I need to be able to do soemthing like this:

Controller:

public async Task<HttpResponseMessage> SendPost(RentalApplication application,string test)

Javascript:

           $http.post("/api/TessIntegration/SendPost", {application:JSON.stringify(application),test:"Some value"}).
            success(function (data, status, headers, config) {
}
like image 311
Denys Wessels Avatar asked Sep 23 '15 05:09

Denys Wessels


2 Answers

You cannot get multiple objects from the body in WebAPI.

If you were passing two complex objects, the solution would be to wrap them into another complex object.

public async Task<HttpResponseMessage> SendPost(SuperComplex request)

public class SuperComplex {
    public Application Application { get; set; }
    public AnotherObject Object { get; set; }
}

$http.post("/api/AController/SendPost", { application: application, Object: {} });

Now if the 2nd parameters is a simple object (such as a string) you can just pass it by queryString instead.

$http.post("/api/AController/SendPost?test=some+value", application );

Also, you don't have to stringify, Angular does it for you.

like image 74
ThiagoPXP Avatar answered Nov 14 '22 23:11

ThiagoPXP


Found a solution using Newtonsoft.Json.Linq.JObject:

Controller:

public async Task<HttpResponseMessage> SendPost(JObject data)
{
    RentalApplication application = data["application"].ToObject<RentalApplication>();
    string test = data["test"].ToObject<string>();
}

Javascript:

        var data = {
            application : application,
            test : "sample value"
        };

        $http.post("/api/TessIntegration/SendPost",data).
        success(function (data, status, headers, config) {

}

like image 38
Denys Wessels Avatar answered Nov 14 '22 23:11

Denys Wessels