4

We have an ASP.NET MVC project in which we make use of jQuery.ajax to post some form data to a controller. In some cases, the controller method being called my run into exceptions due to a bad SQL statement. I'd like to handle the exception in a TRY CATCH and pass back to the user details about why the SQL statement bombed out. Because I'm handling the exception, the jQuery.ajax post is getting an HTTP 200 back from the server, so no errors appear to be happening. If I make use of jQuery.ajax complete property, it seems I'd be able to look for exception details and show the user, but I'm not sure how I can do this from the controller side. Initially I tried something like this on the controller side:

Public Function IndexPost(formvalues as FormCollection) as ActionResult
Try
   ...
Catch ex as Exception
   Dim sErr as String = "Exception occurred: " & ex.ToString
   ViewData("PostResult") = sErr
End Try

Return View()
End Function

And then added this to my jQuery.ajax post:

complete: function (data) {
   var postDataResult = "<%=ViewData("PostResult")%>";
   if (postDataResult.length>2)
   {
      alert("Value of post result: " + postDataResult);
   }
}

ViewData("PostResult") is null of course due to the ajax call.

Any ideas how I can pass a result back to the ajax call from my controller?

Tks

2 Answers 2

3

Create a wrapper class around your response from action methods and have an IsSuccess property on it.In your jQuery post success method, check the IsSuccess property value and do appropriate actions.

Let's create a generic wrapper which can be used for all your viewmodels/response objects.

public class ApiResponse<T>
{
    public bool IsSuccess { set; get; }
    public string ErrorCode { set; get; }
    public string Message { set; get; }
    public T Data { set; get; }
}

Now in your action methods,

public ActionResult Save(CustomerVM model)
{ 
  var response=new ApiResponse<Customer>() { Data= new Customer() };
  try
  {
    //Everythiing went good.
    response.IsSuccess=true;
  }
  catch(Exception ex)
  {
      response.Message="Failed to save";
  }
  return Json(response,JsonRequestBehaviour.AllowGet);
}

At client side

$.post("Save",{ "name" :"SSS"},function(r){
  if(r.IsSuccess)
  {
    //Do something
  }
  else
  {
    //Error occured, 
   alert(r.Message);
  }
});
Sign up to request clarification or add additional context in comments.

1 Comment

Ohh, very nice. Works beautifully. Tks
1

You can use the "Json()" method, which is a "Controller" class method, to return a json object to your ajax post. The Json method expects an object that will be the json object received by your ajax call.

I don't know VB syntax, but it should look like this:

catch ex as Exception
    Dim sErr as String = "Exception occurred: " & ex.ToString
    Dim jsonObject= New With { .success = False, .errorMessage = sErr}
    Return Json(jsonObject, JsonRequestBehavior.AllowGet)
End Try

Then, in javascript you can read it like this:

complete: function (data) {
   if(!data.success) {
      alert("Error message: " + data.errorMessage);
   }
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.