Articles in this section
Category / Section

How to perform server side validation in Grid

1 min read

You can perform the serverside validation using actionBegin event of ejGrid. The following code example shows how to perform server side validation in Grid.

  1. Render the Grid control.

JS

<div id="Grid"></div>
<div id=" ErrorList " title="ErrorList" showOnInit="false"  >
<script type="text/javascript">
    $(function () {// Document is ready.        
        $("#Grid").ejGrid({
            dataSource: window.gridData, 
            allowPaging: true,
            editSettings: { allowEditing: true, allowAdding: true, allowDeleting: true },
            toolbarSettings: { showToolbar: true, toolbarItems: [ej.Grid.ToolBarItems.Add, ej.Grid.ToolBarItems.Edit, ej.Grid.ToolBarItems.Delete, ej.Grid.ToolBarItems.Update, ej.Grid.ToolBarItems.Cancel] },
 
             columns: [
                       { field: "OrderID", headerText: "Order ID", isPrimaryKey: true, width: 100, isIdentity:  true },
                      { field: "CustomerID", headerText: "Customer ID", width: 100 },
                      { field: "Freight", headerText: "Freight", width: 100, format: "{0:C}" },                      
                      { field: "ShipCountry", headerText: "Ship Country", width: 100  }                     
            ],
     actionBegin: "save",
    });
    });
</script>
 

 

 MVC

[In View]
@(Html.EJ().Grid<object>("Grid")  
@Html.EJ().Dialog("ErrorList").Title("ErrorList").ShowOnInit(false)             .Datasource((IEnumerable<object>)ViewBag.data))
            .AllowPaging() 
            .EditSettings(edit => edit.AllowEditing().AllowAdding().AllowDeleting())
            .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("OrderID").IsPrimaryKey(true).IsIdentity(true).Width(100).Add();
                col.Field("CustomerID").HeaderText("Customer ID").Width(100).Add();                
                col.Field("Freight").Width(100).Format("{0:C").Add();                
                col.Field("ShipCountry").HeaderText("Ship Country").Width(100).Add();                
            })
            .ClientSideEvents(eve=>eve.actionBegin ("save"))
)
[Controller]
namespace EJGrid.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            var DataSource = OrderRepository.GetAllRecords();
            ViewBag.data = DataSource;
            return View();
        }        
    }
}

 

ASP.NET

[aspx]
<ej:Dialog ID="ErrorList" ShowOnInit="false" runat="server" Title="ErrorList">
        </ej:Dialog>
<ej:Grid ID="OrdersGrid" runat="server" AllowPaging="True" >  
            <ClientSideEvents ActionBegin="save" />
             <EditSettings AllowEditing="True" AllowAdding="True" AllowDeleting="True" EditMode="Dialog" ></EditSettings>
            <ToolbarSettings ShowToolbar="True" ToolbarItems="add,edit,delete,update,cancel"></ToolbarSettings>           
            <Columns>
                <ej:Column Field="OrderID" HeaderText="Order ID" IsPrimaryKey="True" IsIdentity="True" />                
                <ej:Column Field="CustomerID" HeaderText="Customer ID" />
                <ej:Column Field="Freight" HeaderText="Freight" Format="{0:C}" />
                 <ej:Column Field="ShipCountry" HeaderText="Ship Country" />                
            </Columns>
</ej:Grid>  
[CS]
public partial class _Default : Page
{    
    protected void Page_Load(object sender, EventArgs e)
    {
            this.OrdersGrid.DataSource = new NorthwindDataContext().Orders;
            this.OrdersGrid.DataBind();
    }
}

 

  1.  In actionBegin event, you have passed the edited records value to server side using AJAX post and perform the server side validation.

MVC

 

 
<script type="text/javascript">
    var flag = true;
    function save(args) {
       if (args.requestType == "save" && flag) {
            flag = true;
            var record = args.data;
            args.cancel = true;
            //send ajax post
            $.ajax({
                url: "/Grid/Data",
                type: "POST",
                //dataType: "json",
                contentType: 'application/json; charset=utf-8',
                data: JSON.stringify({ value: record }),
                success: function (data) {
                    var i;                  //display the message when value has duplicate
                    if (data) {
                        var str = "";
                        str += "<tr><td>" + "Value contains Duplicate" + "</td></tr>";
                        $('#ErrorList').html("<table>" + str + "</table>");
                        $('#ErrorList').ejDialog("open");
                    }
                        //save the records if values are not duplicate
                    else {
                        var gridobj = $('#Grid').data("ejGrid");
                        gridobj.endEdit();   //endEdit method called to save records
                        flag = false;
                    }
                },
                error: function (e) {
                    args.cancel = true;
                }
            });
        }
        if (flag == false)
            flag = true;
    }
</script>
 

 

ASP.NET

<script type="text/javascript">
        var flag = true;
     function save(args){
                                   
         if (args.requestType == "save" && flag) {
                flag = true;
                var record = args.data;
                args.cancel = true;
                   //send ajax post
                        $ajax({
                           url: "/Default.aspx/Data",
                          type: "POST",
                          dataType: "json",
                         contentType: 'application/json; charset=utf-8',
                            data: JSON.stringify({ value: record }),
                           
          success: function (data) {
                        var i;                  //display the message when value has duplicate
                        if (data.d) {
                            var str = "";
                            str += "<tr><td>" + "Value contains Duplicate" + "</td></tr>";
                            $('#<%= ErrorList.ClientID %>').html("<table>" + str + "</table>");
                               $('#<%= ErrorList.ClientID %>').ejDialog("open");
                       }
                                                //save the records if values are not duplicate
                       else {
                           var gridobj = $('#<%= OrdersGrid.ClientID %>').data("ejGrid");
                           gridobj.endEdit();   //endEdit method called to save records
                           flag = false;
                       }
                   },
          error: function (e) {
                       args.cancel = true;
                   }
               });
           }
           if (flag == false)
               flag = true;
       }    </script>
 
  1. You can check duplicate values that are existing in the list and returned the Boolean values. And, in AJAX success if the return value is false (Doesn’t have duplicate), we have saved the records to Grid by calling the endEdit method. If the value has duplicate, we have shown the Error message to the dialog box.

MVC

 

  public ActionResult Data(EditableOrder value)
   {
 
            var data = new NorthwindDataContext().OrdersViews.ToList();
            var matchingvalues = data.Where(p => p.CustomerID == value.CustomerID); //checking duplicate values from list
             bool duplicate = false;
              if (matchingvalues.Count() > 0)
                    duplicate = true;  // return true if duplicate values
              return Json(duplicate, JsonRequestBehavior.AllowGet);
            
        }

 

ASP.NET

  public static object Data(Orders value)
        {
            var data = new Order().OrderDetails.ToList();
            var matchingvalues = data.Where(p => p.CustomerID == value.CustomerID); //checking duplicate values from list
            bool duplicate = false;
            if (matchingvalues.Count() > 0)
                duplicate = true;  // return true if duplicate values
            return duplicate;
        }

 

 

 

 The following output is displayed as a result of the above code example.

 

 

Figure: ServerSide Validation in Grid

 

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