Articles in this section
Category / Section

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

2 mins 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.

Solution

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.

@(Html.EJ().Grid<object>("FlatGrid")
        .Datasource(ds=>ds.Json((IEnumerable<object>)ViewBag.datasource).InsertURL("/Grid/PerformInsert").UpdateURL("/Grid/PerformUpdate").RemoveURL("/Grid/PerformDelete").Adaptor(AdaptorType.RemoteSaveAdaptor))
        .AllowPaging()    /*Paging Enabled*/
        .EditSettings(edit => { edit.AllowAdding().AllowDeleting().AllowEditing(); }) /*Editing Enabled*/
        .ToolbarSettings(toolbar =>
        {
            toolbar.ShowToolbar().ToolbarItems(items =>
            {
                items.AddTool(ToolBarItems.Add);
                items.AddTool(ToolBarItems.Edit);
                items.AddTool(ToolBarItems.Delete);
                items.AddTool(ToolBarItems.Update);
                items.AddTool(ToolBarItems.Cancel);
            });
        })
        .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();
            col.Field("ShipCountry").HeaderText("ShipCountry").Width(100).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 
            } 
            OrderRepository.Add(value); 
            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) {
        alert(args.error.getResponseHeader('Exception'));
    }</script>
 

 

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