Articles in this section
Category / Section

How to bind cascading drop down in JavaScript Grid batch editing?

3 mins read

In certain cases, changing the dataSource of one dropdown on selecting a value from other dropdown is known as the cascading effect. This effect can be applied to two dropdown controls within Grid upon editing that is explained in detail in this document. The following discussion 

Render the Grid control in the Batch edit mode and events such as load, cellEdit, and beforeBatchSave.

<div id="Grid"></div>
<script type="text/javascript">
    $(function () {
        $("#Grid").ejGrid({
            dataSource: new ej.DataManager({
                json: window.gridData
            }), 
            load: "load",
            beforeBatchSave: "beforeBatchSave",
            cellEdit: "cellEdit",
            allowPaging: true,
            toolbarSettings: {
                showToolbar: true,
                toolbarItems: ["add","edit","delete","update","cancel"]
            },
            editSettings: { allowEditing: true, allowAdding: true, allowDeleting: true, editMode: "batch" },
            columns: [
                    { field: "OrderID", headerText: "Order ID", isPrimaryKey: true, textAlign: ej.TextAlign.Right },
                    {
                        field: "EmployeeID", headerText: "Employee ID", textAlign: ej.TextAlign.Right, editType: "dropdownedit"
                    },
                    { field: "Freight", format: "{0:C}", textAlign: ej.TextAlign.Right },
                    { field: "CustomerID", headerText: "Customer ID", editType: "dropdownedit" },
                    { field: "ShipCity", headerText: "Ship City" }
            ]
        });
    });
</script>

 

Razor:

 
@(Html.EJ().Grid<OrdersView>("Grid")
    .AllowPaging()
    .Datasource(ds =>
    {
        ds.Json(ViewBag.datasource);
    })
    .EditSettings(edit =>
    {
        edit.AllowAdding().AllowDeleting().AllowEditing().EditMode(EditMode.Batch);
    })
    .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).Add();
        col.Field("EmployeeID").HeaderText("EmployeeID").EditType(EditingType.DropdownEdit)
            .TextAlign(TextAlign.Right).Add();
        col.Field("Freight").HeaderText("Freight")
            .TextAlign(TextAlign.Right)
            .Format("{0:C}").Add();
        col.Field("CustomerID").HeaderText("Customer ID").EditType(EditingType.DropdownEdit).Add();
        col.Field("ShipCity").HeaderText("Ship City").Add();
    })
    .ClientSideEvents(events => events.Load("load").CellEdit("cellEdit").BeforeBatchSave("beforeSave"))
)
 

 

 

 
namespace MvcApplication66.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.datasource = OrderRepository.GetAllRecords().ToList(); 
            return View();
        }
        public ActionResult GetData(int ID)
        {
            List<EditableOrder> userTemplates = OrderRepository.GetAllRecords().Where(c => c.EmployeeID == ID).ToList();
            var data = new List<object>();
            foreach (var Cust in userTemplates)
            {
                data.Add(new { value = Cust.CustomerID, text = Cust.CustomerID });
            }
            return Json(new { data= data, selectedItem = data[0] }, JsonRequestBehavior.AllowGet);
        }     
    }
}

 

Webforms:

    <ej:Grid ID="Grid" runat="server" AllowPaging="true" >
        <EditSettings AllowEditing="True" AllowAdding="True" AllowDeleting="True"></EditSettings>
        <ToolbarSettings ShowToolbar="True" ToolbarItems="add,edit,delete,update,cancel"></ToolbarSettings>
        <Columns>
            <ej:Column Field="OrderID" IsPrimaryKey ="true" TextAlign ="Right" HeaderText="Order ID" />
            <ej:Column Field="EmployeeID" HeaderText="Employee ID" EditType="Dropdown" TextAlign ="Right" />
            <ej:Column Field="Freight" HeaderText="Freight"  />
            <ej:Column Field="CustomerID" HeaderText="Customer ID" EditType="Dropdown"/>
            <ej:Column Field="ShipCity" HeaderText="ShipCity" />
        </Columns>
        <ClienSideEvents Load="load" BeforeBatchSave="beforeSave" CellEdit="cellEdit" db=""></ClienSideEvents>
    </ej:Grid>

 

namespace sqlbinding
{
    public partial class _Default : Page
    {
        public static List<Orders> order = new List<Orders>();
        protected void Page_Load(object sender, EventArgs e)
        {
            Grid.DataSource = order;
            Grid.DataBind();
        }
        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static object GetData(int ID)
        {
            List<EditableOrder> userTemplates = OrderRepository.GetAllRecords().Where(c => c.EmployeeID == ID).ToList();
            var data = new List<object>();
            foreach (var Cust in userTemplates)
            {
                data.Add(new { value = Cust.CustomerID, text = Cust.CustomerID });
            }
            return new { data = data, selectedItem = data[0] };
        } 
   }
}

 

In the load event of the of the Grid, update the editParams of the first dropdown column with the change event and define the change event with the required functionalities such as data collection from server-end and setting the value to the respective cell.

 

Later in the cellEdit event, next dropdown will be set to the dataSource and value. isrowEdited variable maintains the edited row which will be cleared before saving all the records in the beforeBatchSave event.

<script>
    function load(args) {
        //check edited rows
        this.model.isrowEdited = [];
        this.model.columns[1].editParams = $.extend(true, {}, {
            change: function (e) {
                this.element.closest(".e-grid").ejWaitingPopup("show");
                $.ajax({
                    url: 'GetData',
                    type: 'POST',
                    data: { "ID": e.text },
                    success: ej.proxy(function (data) {
                        this.element.closest(".e-grid").ejWaitingPopup("hide");
                        var gridObj = this.element.closest(".e-grid").ejGrid("instance");
                        var inx = gridObj.getIndexByRow(this.element.closest("tr[data-role='row']"));
                        //push edited rows
                        gridObj.model.isrowEdited.push(inx);
                        //set value to the next dropdown column
                        gridObj.setCellValue(inx, "CustomerID", data.selectedItem.text);
                        gridObj.model.columns[3].dataSource = data.data;
                    }, this)
                })
            }
        });
    }
    function beforeSave(args) {
        this.model.isrowEdited = [];
    }
    function cellEdit(args) {
        setTimeout(ej.proxy(function () {
            if (args.columnName == "CustomerID") {
                var inx = this.getIndexByRow(args.row);
                if (this.model.isrowEdited.indexOf(inx) != -1) {
                    //update dataSource and value
                    $("#" + this._id + args.columnName).ejDropDownList({
                        dataSource: ej.dataUtil.distinct(this.model.columns[3].dataSource, "value", true),
                        fields: { text: "text", value: "value" }
                    }).ejDropDownList("setSelectedText", args.value)
                }
            }
        }, this, args), 1)
    }
</script>
 
 
 

 

Figure: Grid Dropdown and Cascaded column in edited state.


Conclusion

I hope you enjoyed learning about how to bind cascading drop down in JavaScript Grid batch editing.

You can refer to our JavaScript Grid featuretour page to know about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our JavaScript Grid example to understand how to create and manipulate data.

For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls.

If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forumsDirect-Trac, or feedback portal. We are always happy to assist you!

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