2

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

2
  • Why not make a complex object with everything in it (including products array, card hash and sender hash)? Commented Mar 13, 2017 at 11:55
  • I can not send an object to api, or at least I am doing it wrong, as it is being shown above. Otherwise, it would be right to ship the ProductModels. Right? Commented Mar 13, 2017 at 12:45

2 Answers 2

2

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
});
Sign up to request clarification or add additional context in comments.

Comments

0

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}"
);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.