0

I am using Asp .Net Core 2.2 to create a shopping cart. So, I want to add items on cart when user clicks Add to Cart button. As you can see the below code is working fine. I have checked "mydata" variable is getting all the data but Json.Stringify(data) doesn't passing any data to controller.

$(".addtocart").click(function (event) {
    event.preventDefault();
    var mydata = {
        "CartItemID": $(this).data("pid"),
        "Name": $("#name").text(),
        "ImageUrl": $("#mainimage").attr("src"),
        "Amount": $("#price").val(),
    };
    $.ajax(
        {
            url: "/cart/add",
            type: "post",
            contentType: "application/json",
            data: JSON.stringify(mydata)
        }
    ).done(function (addresult) {
        $("#cartItemCount").text(addresult.items)
        $("#cartItemCountInner").text(result.Items)
    });
});

Below is the controller code. Model is showing null:

        [HttpPost]
        public ActionResult Add(CartItem item)
         {
            Cart cart = HttpContext.Session.GetObjectFromJson<Cart>("_Cart");
            if (cart == null)
                cart = new Cart();
            cart.Add(item);
            HttpContext.Session.SetObjectAsJson("_Cart", cart);
            JsonResult result = new JsonResult(new { Items = cart.NumberOfItems });
            return result;
}

Please also check the session is used correctly or not because I'm new to Asp .Net Core and don't know much about asp .net core session.

Below is the SessionExtension Code for handling complex object to session:

 public static class SessionExtension
    {
        public static void SetObjectAsJson(this ISession session, string key, object value)
        {
            session.SetString(key, JsonConvert.SerializeObject(value));
        }

        public static T GetObjectFromJson<T>(this ISession session, string key)
        {
            var value = session.GetString(key);
            return value == null ? default(T) : JsonConvert.DeserializeObject<T>(value);
        }
    }
Baqar Abbas
  • 29
  • 2
  • 8
  • 1
    the Json.stringify is redundant. You can just post the object directly. Try removing the json.stringify and just pass the mydata object directly. Also change your controller method to `public ActionResult Add([FromBody] CartItem item)` – Daniel Dec 07 '19 at 01:17
  • Have you configured JsonSerializerSettings in Asp.Net Core Configure method in Startup class? https://stackoverflow.com/questions/35772387/jsonserializersettings-and-asp-net-core – Saineshwar Bageri - MVP Dec 07 '19 at 06:56
  • Could you please share your `CartItem` Model and the view? – Rena Dec 09 '19 at 06:23

1 Answers1

1

Here is a working demo like below:

1.Model:

public class CartItem
{
    public int CartItemID { get; set; }
    public string Name { get; set; }
    public string ImageUrl { get; set; }
    public int Amount { get; set; }
}

2.View:

@model IEnumerable<CartItem>
<table class="table">
    <thead>
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.Name)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.ImageUrl)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Amount)
            </th>
            <th></th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model)
        {
        <tr>
            <td>
                <div id="name">@item.Name</div>
            </td>
            <td>
                <img id="mainimage" src="@item.ImageUrl" />
            </td>
            <td>
                <input id="price" value="@item.Amount" />
            </td>
            <td>
                <input type="button" class="addtocart" data-pid="@item.CartItemID" value="add to cart"/>
            </td>
        </tr>
        }
    </tbody>
</table>
@section Scripts
{
<script>
    $(".addtocart").click(function (event) {
        event.preventDefault();
        var mydata = {
            "CartItemID": $(this).data("pid"),
            "Name": $("#name").text(),
            "ImageUrl": $("#mainimage").attr("src"),
            "Amount": $("#price").val(),
            };
            console.log(JSON.stringify(mydata));
        $.ajax(
            {
                url: "/cart/add",
                type: "post",
                contentType: "application/json",
                data: JSON.stringify(mydata)
            }
        ).done(function (addresult) {
            $("#cartItemCount").text(addresult.items)
            $("#cartItemCountInner").text(result.Items)
        });
});
</script>
}

3.Controller(You need to add FromBody to your action):

    [HttpPost]
    public ActionResult Add([FromBody]CartItem item)
    {
        //...
    }

4.Result: enter image description here

Rena
  • 30,832
  • 6
  • 37
  • 72