Pass two parameters to WEB API call using angular post
Solution 1
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) {
}
Solution 2
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.
Denys Wessels
Updated on June 14, 2022Comments
-
Denys Wessels almost 2 years
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) { }