Articles in this section
Category / Section

How to return Custom message from Controller when CRUD action fails?

1 min read

In some cases, we may like to return a custom message from the controller after completing CRUD operations such that when an operation fails at server side.


We can return the custom message from controller by throwing exception and handling it at client side using the ActionFailure event of the Grid.

Grid Rendering Code.

        .AllowPaging()    /*Paging Enabled*/
        .EditSettings(edit => { edit.AllowAdding().AllowDeleting().AllowEditing(); }) /*Editing Enabled*/
        .ToolbarSettings(toolbar =>
            toolbar.ShowToolbar().ToolbarItems(items =>
        .Columns(col =>
            col.Field("OrderID").HeaderText("Order ID").IsPrimaryKey(true).TextAlign(TextAlign.Right).Width(75).Add();
            col.Field("CustomerID").HeaderText("Customer ID").Width(90).Add();
        .ClientSideEvents(e => e.ActionFailure("failure"))


Code Behind

//Perform insertion  
        public ActionResult PerformInsert(EditableOrder value) 
            if (!ModelState.IsValid) //if validation got failed
                var message = string.Join(" | ", ModelState.Values 
       .SelectMany(v => v.Errors) 
       .Select(e => e.ErrorMessage)); 
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest, message);//message returns the exception content 
            return Json(value, JsonRequestBehavior.AllowGet); 
        //Perform update 
        public ActionResult PerformUpdate(EditableOrder value) 
            if(value.OrderID>300) // check some condition and process update action 
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest, "Data is not valid"); //message returns the exception content 
            return Json(value, JsonRequestBehavior.AllowGet); 


2. Handle the returned message in the ActionFailure event of the Grid.

function failure(args) { 
        alert(args.error.statusText); //get the exception message          


Solution #2: We can also, add the exception message to the response header and fetch the message in the arguments of the ActionFailure event of the Grid at client side.


public ActionResult DataSource(Syncfusion.JavaScript.DataManager dm)
            . . . .
          // if(exception occurs) condition to thrown an exception
           HttpContext.Response.AddHeader("Exception", "Our Exception message");//add exception message to the response header
           Response.StatusCode = 404; //set failure in request.
            . . . .        }


Handle the exception message from the response header using the getResponseHeader method of the args.error argument of the ActionFailure event.

<script type="text/javascript">
    function failure(args) {


Did you find this information helpful?
Help us improve this page
Please provide feedback or comments
Please sign in to leave a comment
Access denied
Access denied