Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get StatusDescription of HttpStatusCodeResult by JavaScript

I have a form created using Ajax.BeginForm()

<% using (Ajax.BeginForm("UpdateCompanyShop", "CompanyShop", FormMethod.Post, 
    new AjaxOptions { OnSuccess = "updateList", OnFailure = "onError",
    UpdateTargetId="slist", LoadingElementId = "loading" }))

controller action code is like below:

if(string.IsNullOrEmpty(company.Address))  
    return new HttpStatusCodeResult(418, "Please fill in address");  
else if (company.DistrictID < 0)  
    return new HttpStatusCodeResult(418, "Please select district");  
else  
    return new HttpStatusCodeResult(418, "Error saving data");

I used OnFailure="onError" in AjaxOptions and I have my client-side script like this

function onError(response, status, error) {  
    var statusDescription = ***something***;  
    alert(statusDescription);
}

I use debugger in the JavaScript but cannot find the StatusDescription (the 2nd parameter in HttpStatusCodeResult)

Any idea how I can get status description? Or I should not use HttpStatusCodeResult at all? What is the proper way to return error (apart from validation) in AJAX submit?

like image 741
newcoder Avatar asked Mar 21 '11 11:03

newcoder


2 Answers

Use response.statusText:

function onError(response, status, error) {
    alert("Oops! " + response.statusText);
}

I wrote a post that provides somewhat more detail and a couple of examples: Dealing with javascript or JSON results after an AJAX call with Ajax.ActionLink, unobtrusive AJAX and MVC 3

like image 113
Sergi Papaseit Avatar answered Oct 16 '22 13:10

Sergi Papaseit


I have the same problem. I think the statusDescription should be response.responseText in the JavaScript OnFailure handler. When you do the following the responseText is not empty, but it's not a really nice solution imo:

Response.StatusCode = 400;
return Json("error message here", JsonRequestBehavior.AllowGet);
like image 22
Marthijn Avatar answered Oct 16 '22 15:10

Marthijn