Diogo Amaral
Diogo Amaral

Reputation: 95

Web Api C# .net params POST

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

Answers (2)

S.Dav
S.Dav

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

Vecchiasignora
Vecchiasignora

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

Related Questions