views:

56

answers:

2

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

        });
A: 

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
}
knepe
Hi Knepe, This is more or less what I am doing in the success function. This allows for only one failure case. If I want to give proper reason for failure, I would not be able to do it in an elegant manner using this method.
mohang
+2  A: 

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);
Rick
triggering the ajax error does the trick. I like this answer.
mohang