How to return an error in an Ajax scenario

前端 未结 2 624
遥遥无期
遥遥无期 2021-01-01 14:46

I am using ASP.NET MVC with jQuery. I have the following MVC Action that returns a partial page on Success. On Application Error, I am not sure what to send it for correctly

相关标签:
2条回答
  • 2021-01-01 15:15

    I would add an error function in your setup of the ajax call. Let the server determine the error message to display and pass it the ajax error handler and let it display it.

    success: function(data, textStatus) {     
        // Clear the local filters first.     
        clearLocalFilters();     
        $('td.selected-filters table.filters-display').append(data);         
    },
    error: function (data) { 
        alert(data.responseText); // use any display logic here
    }
    

    In your controller's action, if an error is found

    Response.StatusCode = (int)HttpStatusCode.BadRequest; 
    return Content(errorMessage, MediaTypeNames.Text.Plain);
    
    0 讨论(0)
  • 2021-01-01 15:19

    I think you can do return Content(false.ToString().ToLower()); if an error is thrown, and then check if data is not false

    if(data != false)
    {
    
        //do stuff
    }
    

    or

    if(!data)
      alert("Error");
    else
    {
      //do stuff
    }
    
    0 讨论(0)
提交回复
热议问题