Search code examples
asp.net-mvc-3jqueryactionmethod

ajax call results in error instead of succes


In my ASP.net mvc3 project, i use a ajax call to send json data to a create actionmethod in the controller Company. But when i debug the ajax call, it always end up in a error result instead of the succes result.

ajax call:

$.ajax({
            url: '/Company/Create',
            type: 'POST',
            data: JSON.stringify(CreateCompany),
            dataType: 'Json',
            contentType: 'application/json; charset=utf-8',
            success: function () {
                alert('ajax call successful');
            },
            error: function () {
                alert('ajax call not successful');
            }
        });

My action method in the Company controller :

    [HttpPost]
    public ActionResult Create (Company company)
    {
        try
        {
            //Create company
            CompanyRepo.Create(company);
            return null;
        }
        catch
        {
            return View("Error");
        }
    }

I already debugged the actionmethod, but he completes it like he should. So the data send with the ajax call will be handled and written to the db. (the action method does not use the catch part).

Why is my ajax call still gives the message 'ajax call not succesful'?


Solution

  • I used to got same problem with getting back the JSON result. What I did is to set the dataType to "text json" :)) If this doesn't help try to get additional info by acquiring details of your error, i.e.:

    $.ajax({
            url: '/Company/Create',
            type: 'POST',
            data: JSON.stringify(CreateCompany),
            dataType: 'text json',
            contentType: 'application/json; charset=utf-8',
            success: function () {
                alert('ajax call successful');
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert("XMLHttpRequest=" + XMLHttpRequest.responseText + "\ntextStatus=" + textStatus + "\nerrorThrown=" + errorThrown);
            }
        });
    

    BTW: I found this solution somewhere on the StackOverflow