开发者

ajax call results in error instead of succes

开发者 https://www.devze.com 2023-03-03 00:16 出处:网络
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 er开发者_StackOverflowror resu

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 er开发者_StackOverflowror 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'?


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

精彩评论

暂无评论...
验证码 换一张
取 消