Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return JSON object when Bad Request MVC

I am working on MVC 4 project.

I have a Action which executed when Ajax Post request is done.

In some case, which I could exactly determine, I have to set the Status property of the Response object to HttpBadRequest value, AND return JSON object which contains some data to show to the end user.

the problem is I can NOT received the JSON object in the javascript method, I am receiving something else. and this is because I am setting the Status property of the Response to HttpBadRequest value.

Here is the Details

Action

// this method will executed when some Ajax Post request.
[HttpPost]
public ActionResult Delete(int id)
{
    // some code here ......

    // in some case we will determine an error like this
    if(error)
    {
        HttpContext.Response.Clear();
        HttpContext.Response.TrySkipIisCustomErrors = true;
        HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;

        return Json(new
        {
            Message = string.Format(format, values),
            Status = messageType.ToString()
        });
    }
}

and I want to read this returned JSON object from a javascript function like this

Javascript

function OnDeleteFailed(data) {
    debugger;
    var try1 = $.parseJSON(data.responseText);
    var try2 = JSON.parse(data.responseJSON);
}

the problem is that the JSON object will NOT filled in the data variable of the javascript. when debugging the Javascript code I get the following in the data variable

enter image description here

The most strange thing that when I delete this line from the Action

HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;

then I received the JSON object correctly and I could to read it as the following

enter image description here

Note: I am receiving the correct JSON object but, in other Javascript function. (now I am receiving the JSON object on the OnDeleteSuccess function, not in OnDeleteFailed function.

So The Question is : what the wrong with the code, so the JSON object will not received in the javascript function in case I set the "StatusCode" property of the "Response" object to "BadRequest" value ?

I searched a lot for an answer (from yesterday until now), and after long searching this is the most relevant question to me, but unfortunately the solution of that question did not worked for me at all.

Updated

here is snippet of the Web.config file which set some of httpErrors of the IIS. This update to respond for the suggestion that the cause of the error will come from this point

<system.webServer>
   <httpErrors errorMode="Custom" existingResponse="Replace">
      <remove statusCode="404" />
      <error statusCode="404" responseMode="ExecuteURL" path="/Home/PageNotFound" />
   </httpErrors>
</system.webServer>

Any ideas will be appreciated.

like image 279
Hakan Fıstık Avatar asked Oct 15 '15 10:10

Hakan Fıstık


People also ask

How do I return a Bad Request JsonResult?

If you'd like to return a JSON object with a response type of application/json , then you should pass an object that isn't a string to BadRequest() . You can even pass an anonymous object to quickly create a JSON object like so: return BadRequest(new { message = "bad request"});

Can ActionResult return JSON?

JsonResult is one of the type of MVC action result type which returns the data back to the view or the browser in the form of JSON (JavaScript Object notation format).

What does JsonResult return?

Format-specific Action Results For example, returning JsonResult returns JSON-formatted data. Returning ContentResult or a string returns plain-text-formatted string data. An action isn't required to return any specific type.


1 Answers

In your Web.Config, try to change existingResponse to Auto:

<httpErrors errorMode="Custom" existingResponse="Auto">

See Documentation

like image 143
haim770 Avatar answered Oct 02 '22 23:10

haim770