ajax call results in error instead of succes

2020-04-12 10:02发布

问题:

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

回答1:

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



回答2:

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 });


回答3:

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
    });
}