ajax call results in error instead of succes

北城余情 提交于 2019-12-02 01:41:21

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

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

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
    });
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!