Implement Onfailure in webApi controller

61 views Asked by At

I have a Web Api in which I have this code

                   @{
                    AjaxOptions addAjaxOpts = new AjaxOptions
                    {
                        // options will go here
                        OnSuccess = "getData", 
                        OnFailure="selectView('add')",
                        HttpMethod = "Post",
                        Url = "/api/AccountManage/CreateAccount"
                    };
                }

In the controller :

[HttpPost]
        public void CreateAccount(CollaborateurModel item)
        {
        try{}
        catch{
             // return failure
             }
         }           

I need to implement failure part to execute OnFailure method .

So how can I accomplish this task?

2

There are 2 answers

3
Thiago Avelino On BEST ANSWER

You can start by using Json Result (MSDN ref.)

Snippet example:

[HttpPost]
public ActionResult CreateAccount(CollaborateurModel item)()
{
    try{
      //do operations that may fail
      var response = new { Success = true};
      return Json(response );
    }catch{
      var errorResponse= new { Success = false, ErrorMessage = "error"};
      return Json(errorResponse);
    }

}

Then on the client side you call the controller using JQuery:

$(function () {
   $(".test-link").click(function (e) {
      $.post("controllerName/CreateAccount", function (data) {
        if (data.Success == true) {
           alert("Success");
         }
         else {alert(data.ErrorMessage);}
       });
       return false;
    }).fail(function() {
      alert( "error" );
     });
});

The fail function on Jquery will handle communication problems that you may have with client-server.

More info about JQuery you can find it here.

0
Snelbinder On

Depending on your desired response status code, you can use the BadRequest, NotFound or InternalServerError result classes. Each of these have a constructor that has an optional parameter for an error message.

[HttpPost]
public IHttpActionResult CreateAccount(CollaborateurModel item)
{
    try
    {
        // Do your thing
    }
    catch
    {
        // Return a HTTP 400 result
        return BadRequest("This is an error message");
    }
}