简体   繁体   中英

Getting 400 Response Error Message in JS

I have a dot net MVC controller that returns a 400 response with an error message when there's obviosuly a bad request, as seen below:

return new HttpStatusCodeResult(HttpStatusCode.BadRequest, "This is a bad request");

This controller is hit through the JQuery Post method

    $.post({
    url: window.location.href,
    type: 'POST',
    contentType: 'application/json',
    data: JSON.stringify(payload),
    success: function (data) {
        window.location.href = data;
    },
    error: function (jqXHR, textStatus, errorThrown) {
        $('.submit-calculate').html(jqXHR.responseText);
        debugger;
    }};

My issue is that the string I return when returning the HttpStatusCodeResult string property is inaccessible. The jqXHR has a property response text which contains a HTML page for a 400 response, which renders the following on the page:

在此处输入图片说明 Now the error message is display within this HTML but I want to just access that string ( "This is a bad request" ) without having to pull it out of that response. Not sure if there's a property that I can't see right now or I need to return something different.

You can use JsonResult class to return JSON result

Response.StatusCode = (int)HttpStatusCode.BadRequest;
return new JsonResult(){
      Data = "This is a bad request"
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM