Reputation: 213
I'm trying to get filtered data from server using a filtering object I pass to the server side. I have managed to get this working with a post:
angular:
var filter: { includeDeleted: true, foo: bar };
$http({ method: 'post', url: 'api/stuff', data: filter });
web api:
public IEnumerable<StuffResponse> Post([FromBody]Filter filter)
{
return GetData(filter);
}
But i don't want to use a post for this, I want to use a get. But this does not work:
angular
$http({ method: 'get', url: 'api/stuff', params: filter });
web api
public IEnumerable<StuffResponse> Get([FromUri]Filter filter)
{
return GetData(filter);
}
Also tried specifying params: { filter: filter }. If i try [FromBody] or nothing, filter is null. With the FromUri i get an object at least - but with no data. Any ideas how to solve this, without creating input parameters for all filter properties?
Upvotes: 4
Views: 19877
Reputation: 604
you can send object with Get or Post method .
Script
//1.
var order = {
CustomerName: 'MS' };
//2.
var itemDetails = [
{ ItemName: 'Desktop', Quantity: 10, UnitPrice: 45000 },
{ ItemName: 'Laptop', Quantity: 30, UnitPrice: 80000 },
{ ItemName: 'Router', Quantity: 50, UnitPrice: 5000 }
];
//3.
$.ajax({
url: 'http://localhost:32261/api/HotelBooking/List',
type: 'POST',
data: {order: order,itemDetails: itemDetails},
ContentType: 'application/json;utf-8',
datatype: 'json'
}).done(function (resp) {
alert("Successful " + resp);
}).error(function (err) {
alert("Error " + err.status);});
API Code
[Route("api/HotelBooking/List")]
[HttpPost]
public IHttpActionResult PostList(JObject objData)
{ List<ItemDetails > lstItemDetails = new List<ItemDetails >();
dynamic jsonData = objData;
JObject orderJson = jsonData.itemDetails;
return Ok();}
Upvotes: 0
Reputation: 840
Yes you can send data with Get method by sending them with params
option
var data ={
property1:value1,
property2:value2,
property3:value3
};
$http({ method: 'GET', url: 'api/controller/method', params: data });
and you will receive this by using [FromUri]
in your api controller method
public IEnumerable<StuffResponse> Get([FromUri]Filter filter)
{
return GetData(filter);
}
and the request url will be like this
http://localhost/api/controller/method?property1=value1&property2=value2&property3=value3
Upvotes: 5
Reputation: 1994
Solved it this way:
Angular:
$http({
url: '/myApiUrl',
method: 'GET',
params: { param1: angular.toJson(myComplexObject, false) }
})
C#:
[HttpGet]
public string Get(string param1)
{
Type1 obj = new JavaScriptSerializer().Deserialize<Type1>(param1);
...
}
Upvotes: 4
Reputation: 38663
A HTTP GET
request can't contain data to be posted to the server. What you want is to a a query string to the request. Fortunately angular.http
provides an option for it params
.
See : http://docs.angularjs.org/api/ng/service/$http#get
Upvotes: 2