AP123
AP123

Reputation: 57

Error 500 internal server error in asp.net

I am writing an asp.net application and am trying to make a post request using jquery ajax to web api2 controller method. Doing so results in error 500 internal server error. Here is the jquery code

function reload(quantity, cartItemId) {
        $.ajax({
            url: "/api/user/UpdateCart",
            method: "POST",

            data: { quantity: quantity, cartItemId:cartItemId },
            success: function() {
              //  window.location.href = "/user/ViewCart";
            }

    });
    }

    function addItem(cartItemId) {
        var quantity = parseInt(document.getElementById("txt-box-" + cartItemId).value);
        quantity++;
        document.getElementById("txt-box-" + cartItemId).value = quantity;
        reload(quantity,cartItemId);
    }

In my web api 2 controller I have the following code

    [AllowAnonymous]
    [HttpPost]
    public IHttpActionResult UpdateCart([FromBody]int quantity,[FromBody]int cartItemId)
    {
        var cartItemInDb = _unitOfWork.CartItemRepository.Read(cartItemId);
        cartItemInDb.Quantity = quantity;
        _unitOfWork.Complete();

        return Ok();
    }

Upvotes: 0

Views: 971

Answers (1)

Bhaskar Shanbhag
Bhaskar Shanbhag

Reputation: 71

I dont think webapi allows multiple frombody parameters. When I tried with your code, I got this error - "Can't bind multiple parameters ('quantity' and 'cartItemId') to the request's content.". When there are binding issues, your function will not be hit in visual studio as it will return from the pipeline itself.

Also, as per design too, you can have quantity and cartItemId and change your code as below:

Controller code:

    [AllowAnonymous]
    [HttpPost]
    [Route("api/user/UpdateCart")]
    public IHttpActionResult UpdateCart([FromBody]CartDetails cartDetails)
    {
        Console.WriteLine(cartDetails.cartItemId);
        Console.WriteLine(cartDetails.quantity); // Your code instead of Console.WriteLine();

        return Ok();
    }

class:

public class CartDetails
{
    public int quantity;
    public int cartItemId;
}

ajax call in javascript:

        $.ajax({

        url: "http://localhost:49946/api/user/UpdateCart",
        method: "POST",
        contentType: "application/json",
        data: JSON.stringify(
            {
                quantity: 12, cartItemId: 109
        }),
        success: function (result) {
            console.log("SUCESS: " + result);
        },
        error: function (data) {
            console.log("error: " + data.responseText);
        }
    });

Upvotes: 1

Related Questions