.NET Web API and jQuery AJAX (500 Internal Server Error)

nightshadz
nightshadz used Ask the Experts™
on
I'm trying to build a SPA using jQuery AJAX and .NET Web Services and I am stuck trying to figure out why my ajax call is returning a 500 internal server error.

Assume id = 0 and an instance of a shopping list is returned to the ajax call. For some reason it is always hitting the error handler and showing "something went wrong".

JS code:
function getShoppingListById(id) {
    console.info(id);

    $.ajax({
        type: "GET",
        dataType: "json",
        url: "api/ShoppingList/" + id,
        success: function(result) {
            currentList = result;
            showShoppingList();
            drawItems();
        },
        error: function() {
            console.error("Something went wrong");
        }
    });
}

$(document).ready(function () {
    console.info("ready");
    $("#shoppingListName").focus();
    $("#shoppingListName").keyup(function(event) {
        if (event.keyCode === 13) {
            createShoppingList();
        }
    });

    var pageUrl = window.location.href;
    var idIndex = pageUrl.indexOf("?id=");
    if (idIndex !== -1) {
        getShoppingListById(pageUrl.substring(idIndex + 4));
    }
});

Open in new window


C# code:
        
public IHttpActionResult Get(int id)
        {
            var result = shoppingLists.FirstOrDefault(s => s.Id == id);

            if (result == null)
            {
                return NotFound();
            }

            return Ok(result);
       }

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2017
Distinguished Expert 2018
Commented:
A 500 server error means there was an error on the server - your server script crashed / encountered a bug.

Before testing your AJAX script (given this is a GET) first get it working using the browser. Type the URL into a browser window and test until you get back the correct results - then go back to your AJAX script.

The issue here has nothing to do with AJAX and everything to do with you server script - so debug that first - when it is working - go back to AJAX.

Trying to debug at the AJAX level is just adding an extra level of complexity that is not needed.

Make sure you have error reporting on, check your logs, if you are using IE make sure the option to show friendly error messages is on, on IIS make sure you have enabled the option to send errors to the browser.

Author

Commented:
Thanks! The issue was that I had another controller method that started with Get so .NET did not know which api to call.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial