Home Error 500 internal server error in asp.net
Reply: 1

Error 500 internal server error in asp.net

AP123
1#
AP123 Published in 2018-01-12 14:20:39Z

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();
    }
Bhaskar Shanbhag
2#
Bhaskar Shanbhag Reply to 2018-01-12 18:05:38Z

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);
        }
    });
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.328172 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO