2

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'?

Thomas
  • 297
  • 1
  • 8
  • 21
  • Have you tried debugging with Firebug to see what actually happens behind the scenes with the request/response process? – Gup3rSuR4c May 03 '11 at 09:44

3 Answers3

4

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

Julian S
  • 215
  • 2
  • 7
  • unbelievable that this changes a lot! I changed datatype to 'text json' and now it gives me the function in the success part. – Thomas May 03 '11 at 09:59
  • I spent quite amount of time when first time looking for the answer. Glad I could help :) – Julian S May 03 '11 at 10:03
1

Why are you returning null in case of success in your controller action? Return something to success like for example a JSON object (especially as you indicated in your AJAX request that you expect JSON response from the server - using the dataType: 'json' setting - which should be lowercase j by the way):

return Json(new { success = true });
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • What you said, and I think the `contentType` part of the Ajax call is pointless as well. Furthermore, if there's a `{success = true}` for the try, then there should be a `{success = false}` for the catch, and thus the whole action can be marked as a `JsonResult`. – Gup3rSuR4c May 03 '11 at 09:50
0

Wouldn't this just be easier:

$.post("/Company/Create", function (d) {
    if (d.Success) {
        alert("Yay!");
    } else {
        alert("Aww...");
    }
}, "json");

And in your controller.

[HttpPost]
public JsonResult Create(
    [Bind(...)] Company Company) { <- Should be binding
    if (this.ModelState.IsValid) { <- Should be checking the model state if its valid
        CompanyRepo.Create(Company);

        return this.Json(new {
            Success = true
        });
    };

    return this.Json(new {
        Success = false
    });
}
Gup3rSuR4c
  • 9,145
  • 10
  • 68
  • 126
  • $.post is easier to code, but with .ajax you have greater depth of configuration, error handling, .. – Thomas May 03 '11 at 10:22