2

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.

17
  • 1
    So...what doesn't work? Did you check the browser console to see if there's any errors? Did you check what's actually being posted? We need some more details. Commented Aug 13, 2020 at 14:42
  • @Nikki9696 I do not have any errors in my browser console.The thing is I got stuck at this step, I formed my JSON object and now I'm trying to pass it to my Controller in order to create my C# object and then later add it to my database.Where can I see what's being posted? Commented Aug 13, 2020 at 15:10
  • Put a breakpoint in your controller method. Commented Aug 13, 2020 at 15:19
  • @ballonDor, run your api in debugging mode (F5 in VS) and place breakpoint at opening brace. By the way, you don't need to mark your parameter with [FromBody]. If action methods accept complex objects as parameter WebAPI uses registered MediaTypeFormatters for binding. Media type formatter for json content type is included by default in WebAPI. Commented Aug 13, 2020 at 15:21
  • 1
    @ballonDor, now remove last url segment in ajax call. Url should look as "api/shopping. By default WebApi specifies calling method by HTTP Method type (GET, POST, etc.) , if no routing explicit specified. Commented Aug 13, 2020 at 19:30

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

16 Comments

Tried both of these methods and none seems to work.
@ballonDor, please provide us with your controller code in its entirety, as well as the Configure method in your starup.cs file.
public void ConfigureServices(IServiceCollection services) { services.AddDbContext<AppDbContext>(option => option.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); services.AddControllersWithViews(); services.AddRazorPages().AddRazorRuntimeCompilation(); services.AddControllersWithViews().AddNewtonsoftJson(); services.AddControllersWithViews(options => { options.InputFormatters.Insert(0, GetJsonPatchInputFormatter()); }); }
The controller code is just the same code that I posted before.Also I mapped the Controllers like this: app.UseEndpoints(endpoints => { endpoints.MapControllers(); endpoints.MapRazorPages(); });
Managed to solve the problem everything works fine.Just as expected thank you so much for the help!!!Much appreciated.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.