ballonDor
ballonDor

Reputation: 47

Posting JSON object via AJAX to ASP.NET Core Web API

I have tried different methods that have been posted on this site, but nothing seems to work. I want to create a clothing site (a personal project). The products on the site have their own class, that is built like this:

 public class Product
 {
      public string ProductName { get; set; }
      public string ProductPrice { get; set; }

      public int Quantity { get; set; }
 }

The shopping cart is another class that will contain a list of Product objects and this one is built like this:

public class ShoppingCart
{
    [Key]
    public int Id { get; set; }
    List<Product> ProductList { get; set; }

    public string ClientName { get; set; }

    public string ClientAddress { get; set; }

    public string ClientMail { get; set; }
}

I created an API Controller class and thought that would solve the problem. It looks like this:

[Route("api/Shopping")]
[ApiController]
public class ShoppingCartController : ControllerBase
{
    [HttpPost]
    public ShoppingCart Save([FromBody] ShoppingCart s)
    {
        return s;
    }
}

In my JavaScript code I create my JSON object and try to post it like this:

 var orderB = document.getElementById("orderB");
    orderB.addEventListener("click", function () {
        var inputName = document.getElementById("inputName").value;
        var inputAddress = document.getElementById("inputAddress").value;
        var inputMail = document.getElementById("inputMail").value;
        var auxArray = [];

        for (var i = 0; i < productsAux.length; i++) {
            auxArray[i] = { "productName": productsAux[i].titlu, "productPrice": productsAux[i].pret, "quantity": localStorage.getItem(productsAux[i].titlu)};
        }

        var shoppingCart = {
            productList: auxArray,
            clientName: inputName,
            clientAddress: inputAddress,
            clientMail: inputMail
        };

        $.ajax({
            type: "POST",
            data: JSON.stringify(shoppingCart),
            url: "api/shopping/save",
            contentType: "application/json charset=utf-8",
             }).done(function (res) {
            alert(res);
        });
       

After I push the order button on my page I expect to see the alert pop-up with the callback result which I suppose is the ShoppingCart object that is created using the JSON that I send.

Upvotes: 2

Views: 11578

Answers (2)

LuvForAirplanes
LuvForAirplanes

Reputation: 781

For those coming on later, I would suggest checking that your types are correct on both ends. For instance, if your JS is posting a byte array and C# tries to convert it to an int, the whole object (not just that prop) will be null.

This has caught me many a time.

Upvotes: 3

LouraQ
LouraQ

Reputation: 6891

I opened the Network tab and I got this: I got a 404 (kind of expected that) , the name of the method 'save' , a type of 'xhr' and a size of 45B.

The 404 error obviously means the url/routing is wrong. Here to solve it ,you have two ways to achieve.

First way:

You can change url to "api/shopping" in ajax as follow:

        $.ajax({
                type: "POST",
                data: JSON.stringify(shoppingCart),
                url: "api/shopping",
                contentType: "application/json charset=utf-8",
            }).done(function (res) {
                alert(res);
            })

Second way:

You can change the path name of Save action by Attribute routing with Http verb attributes as follow:

            [Route("api/Shopping")]
            [ApiController]
            public class ShoppingCartController : ControllerBase
            {
                [HttpPost("Save")]
                public ShoppingCart Save([FromBody] ShoppingCart s)
                {
            
                    return s;
                }
            }

Update

According to your comment, in addition to the above updates, you also need to modify the routing settings as follows:

 app.UseEndpoints(endpoints =>
 {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}"); 
 });

Debug result:

enter image description here

Upvotes: 1

Related Questions