Reputation: 95
I'm trying to send a list of products for my web api in C# via JavaScript but my API doesn't accepts the products. How do I should pass it?
This is my model
public class ProductModels
{
public int productId { get; set; }
public string description { get; set; }
public int quantity { get; set; }
public decimal amount { get; set; }
}
and my API endpoint
[Route("api/pag_seguro/transactions/credit_card")]
public IHttpActionResult DoTransactionWithCreditCard(ProductModels[] products, string senderHash, string cardHash)
in Javascript I'm trying to send it like this
data.products = [{ "productId": 1, "description": "tupperware", "quantity": 1, "amount": 29.80 }];
$.ajax({
type: 'POST',
url: url + '/api/pag_seguro/transactions/credit_card?cardHash=' + cardHash + '&senderHash=' + senderHash,
data: data,
success: function (response) {
console.log(response);
},
dataType: 'json',
async: false
});
and still about this endpoint... how do I send the senderHash and cardHash as POST parameters so that than doesn't appears in web url?
Thank you all
Upvotes: 2
Views: 215
Reputation: 2466
You need to set the content type in the request as
contentType:"application/json"
Also, use JSON.stringify
to convert the data to JSON format when you send.
Try this code:
$.ajax({
type: 'POST',
url: url + '/api/pag_seguro/transactions/credit_card?cardHash=' + cardHash + '&senderHash=' + senderHash,
data: JSON.stringify(data),
contentType: "application/json",
success: function (response) {
console.log(response);
},
dataType: 'json',
async: false
});
Upvotes: 2
Reputation: 1315
try this
public IHttpActionResult DoTransactionWithCreditCard([FromUri] SiteInfo, siteInfoProductModels[] products)
and your siteinfo model is
public class SiteInfo
{
public string senderHash { get; set; }
public string cardHash { get; set; }
}
finally remove your route from action header and add new route in webapiconfig.cs like this (and change js file set params liek this /param1/param1 )
config.Routes.MapHttpRoute(
name: "HashRoute",
routeTemplate: "api/{controller}/{action}/{senderHash}/{cardHash}"
);
Upvotes: 0