How to return an error in an Ajax scenario

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 handling it at the client side:

public ActionResult LoadFilterSet(int filterSetId)
{
    try
    {
        BreadCrumbManager bcManager = this.ResetBreadCrumbManager(this.BreadCrumbManagerID);
        GeneralHelper.LoadBreadCrumbManager(bcManager, filterSetId);

        ViewData["BreadCrumbManager"] = bcManager;
        return View("LoadFilterSet");
    }
    catch (Exception ex)
    {
        return Content("");
    }
}

Following is my jQuery ajax call. Notice that I am checking for the data length to make sure there are no errors. Please suggest me a better way of doing this.

$.ajax({
    type: "GET",
    dataType: "html",
    async: true,
    data: ({ filterSetId: selectedId }),
    url: link,
    contentType: "text/html; charset=utf-8",
    success: function(data, textStatus) {
        if (data.length > 0) {
            // Clear the local filters first.
            clearLocalFilters();
            $('td.selected-filters table.filters-display').append(data);
        }
    }
});

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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

Method 2

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
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x