Articles in this section
Category / Section

Show DropDown with CRUD action list in JavaScript Grid.

1 min read

This Knowledge Base explains the way, to place the dropdown by customizing the toolbar and to perform CRUD operations based on the selected item from the dropdown instead of showing individual items in toolbar.instead of rendering the default toolbar icons in JavaScript Grid.

 

HTML

                   <div id="Grid"></div>         

 

JS

    <script type="text/javascript">
        $(function () {
            var data = ej.DataManager(window.gridData).executeLocal(ej.Query().take(50));
            $("#Grid").ejGrid({
                dataSource: data,
                allowPaging: true,
                editSettings: { allowEditing: true, allowAdding: true, allowDeleting: true, editMode: ej.Grid.EditMode.Normal },
                toolbarSettings: { showToolbar: true, customToolbarItems: [{ templateID: "#crudoperation" }] },
                columns: [
                         { field: "OrderID", headerText: "Order ID", width: 75, textAlign: ej.TextAlign.Right },
                         { field: "CustomerID", headerText: "Customer ID", width: 80 },
                         { field: "EmployeeID", headerText: "Employee ID", width: 75, textAlign: ej.TextAlign.Right },
                         { field: "Freight", width: 75, format: "{0:C}", textAlign: ej.TextAlign.Right },
                         { field: "OrderDate", headerText: "Order Date", width: 80, format: "{0:MM/dd/yyyy}", textAlign: ej.TextAlign.Right },
                        ],
                recordClick: "cellselected",
                dataBound:"databound"
            });
       });
 </script>
 
<script id="crudoperation" type="text/x-jsrender">
             <input id="DropDownList" />
             <ul id="crudoperationscrudaction">
                 <li>Add</li>
                 <li>Update</li>
                 <li>Delete</li>
                 <li>Cancel</li>
                 <li>Edit</li>
             </ul>
</script>
 
<script type="text/javascript">
           function databound(args) {
                $('#DropDownList').ejDropDownList({
                    targetID: "crudactioncrudoperations",
                    select: change,
                    create: create,
                });
            }
</script>

 

Razor

@(Html.EJ().Grid<SyncfusionMvcApplication20.OrdersView>("Grid")
 
        .Datasource((IEnumerable<object>)ViewBag.datasource)
 
        .ToolbarSettings(tool => tool.ShowToolbar().CustomToolbarItems(new List<object>() { new Syncfusion.JavaScript.Models.CustomToolbarItem() { TemplateID = "#crudoperation" } }))
 
        .AllowPaging()    /*Paging Enabled*/
 
       .EditSettings(edit => { edit.AllowAdding().AllowDeleting().AllowEditing().EditMode(EditMode.Normal); })
        
        .Columns(col =>
        {
            col.Field("OrderID").HeaderText("Order ID").IsPrimaryKey(true).TextAlign(TextAlign.Right).Width(75).Add();
            col.Field("CustomerID").HeaderText("Customer ID").Width(80).Add();
            col.Field("EmployeeID").HeaderText("Employee ID").TextAlign(TextAlign.Right).Width(75).Add();
            col.Field("Freight").HeaderText("Freight").TextAlign(TextAlign.Right).Width(75).Format("{0:C}").Add();
            col.Field("OrderDate").HeaderText("Order Date").TextAlign(TextAlign.Right).Width(80).Format("{0:MM/dd/yyyy}").Add();
 
        })
 
                .ClientSideEvents(eve => eve.RecordClick("cellselected"))
)
 
 
 
<script id="crudoperation" type="text/x-jsrender">
    @Html.EJ().DropDownList("DropDownList").Datasource((IEnumerable<object>)ViewData["DropDownDataSource"]).DropDownListFields(Df => Df.Text("Text").Value("Value")).Height("30px").Width("150px").ClientSideEvents(e => e.Select("change").Create("create"))
 
</script>

 

C#

 

namespace Sample.Controllers
{
    public class GridController : Controller
    {
        public ActionResult GridFeatures()
        {
            var DataSource = new NorthwindDataContext().OrdersViews.ToList();
            ViewBag.datasource = DataSource;
            List<Data> DropdownData = new List<Data>();
            DropdownData.Add(new Data { Value = "Add", Text = "Add" });
            DropdownData.Add(new Data { Value = "Update", Text = "Update" });
            DropdownData.Add(new Data { Value = "Delete", Text = "Delete" });
            DropdownData.Add(new Data { Value = "Cancel", Text = "Cancel" });
            DropdownData.Add(new Data { Value = "Edit", Text = "Edit" });
            ViewData["DropDownDataSource"] = DropdownData;
          
            return View();
        }
     }
}

 

ASPX

<ej:Grid ID="Grid" runat="server" AllowPaging="True">
                    <ClientSideEvents RecordClick="cellselected" />
                    <Columns>
                        <ej:Column Field="OrderID" HeaderText="Order ID" IsPrimaryKey="true" Width="90">
                        </ej:Column>
                        <ej:Column Field="CustomerID" HeaderText="CustomerID" Width="110"></ej:Column>
                        <ej:Column Field="EmployeeID" HeaderText="EmployeeID" Width="110"></ej:Column>
                        <ej:Column Field="Freight" HeaderText="Freight" Width="90"></ej:Column>
                        <ej:Column Field="OrderDate" HeaderText="OrderDate" Width="90"></ej:Column>
                    </Columns>
                    <EditSettings AllowEditing="True" AllowAdding="True" AllowDeleting="True" EditMode="Normal"></EditSettings>
                    <ToolbarSettings ShowToolbar="True">
                        <CustomToolbarItem>
                            <ej:CustomToolbarItem TemplateID="#crudoperation" />
                        </CustomToolbarItem>
                    </ToolbarSettings>
                </ej:Grid>
 
<script id="crudoperation" type="text/x-jsrender">
        <ej:DropDownList ID="DropDownList" runat="server" Height="30px" Width="150px" ClientSideOnSelect="change" ClientSideOnCreate="create">
            <Items>
                <ej:DropDownListItem Text="Add" Value="Add"></ej:DropDownListItem>
                <ej:DropDownListItem Text="Update" Value="Update"></ej:DropDownListItem>
                <ej:DropDownListItem Text="Delete" Value="Delete"></ej:DropDownListItem>
                <ej:DropDownListItem Text="Cancel" Value="Cancel"></ej:DropDownListItem>
                <ej:DropDownListItem Text="Edit" Value="Edit"></ej:DropDownListItem>
            </Items>
        </ej:DropDownList>
    </script>

 

Using the create event of dropdown, we can disable some of the items like update, cancel at the initial load of dropdown as like it is done in the default toolbar icons of grid at the initial rendering

In the change event of dropdown, based on args.text value perform the CRUD operations with using some CRUD public methods of grid.

Example:

 In the change event of dropdown, for adding the a new row for grid it is enough to call the addRecord method of grid when args.text contains value is “add”.

<script type="text/javascript">
    var selectedcellfield;
    var DDinstance;
     function cellselected(args){
        var obj = $("#Grid").ejGrid("instance");
        selectedcellfield = obj.getFieldNameByHeaderText(args.columnName);
     }
     function create(args) {
         var DropDownListObj = $("#DropDownList").data("ejDropDownList");
         DDinstance = DropDownListObj;                    //Rendering the DropDown at the initial time
         DropDownListObj.disableItemsByIndices("1,3");
       }
    function change(args) {
        var grid = $(".e-grid").ejGrid("instance");
        if (args.text == "Add") {
            DDinstance.disableItemsByIndices("0,2,4");
            DDinstance.enableItemsByIndices("1,3");  
            grid.addRecord();                                                    //Perform add operation when clicking add in dropdown
        }
        if (args.text == "Edit") {
             if (grid.getSelectedRecords().length > 0) {
                DDinstance.disableItemsByIndices("0,2,4");
                DDinstance.enableItemsByIndices("1,3");
                 if (grid.model.editSettings.editMode != "batch") {
                        grid.startEdit();
                    }
                    else
                        grid.editCell(grid.model.selectedRowIndex, selectedcellfield);    //Perform Edit operation
                }
                else
                    alert("Select any row to edit");
            }
        if (args.text == "Delete") {
            DDinstance.disableItemsByIndices("1,3");
                if (grid.getSelectedRecords().length > 0) {
                    grid.deleteRecord("OrderID", grid.model.currentViewData[grid.model.selectedRowIndex])
                                                                                  //Perform delete operations.
                }
                else
                    alert("No records selected for delete operation");
            }
            if (args.text == "Update") {
                DDinstance.disableItemsByIndices("1,3");
                DDinstance.enableItemsByIndices("0,2,4");
                if (grid.model.editSettings.editMode != "batch")
                    grid.endEdit();                                                 //perform update action
                else
                    grid.batchSave();
            }
            if (args.text == "Cancel") {
                DDinstance.disableItemsByIndices("1,3");
                DDinstance.enableItemsByIndices("0,2,4");
                if (grid.model.editSettings.editMode != "batch")
                    grid.cancelEdit();                                                //cancel the editing when clicking cancel in dropdown
                else
                    grid.batchCancel();
            }
        }
</script>

 

C:\Users\Manisankar.durai\Desktop\sshot-1.png

Figure 1: Aadding the Data/Rows to the grid using dropdown.

C:\Users\Manisankar.durai\Desktop\sshot-2.png

Figure 2: Shown alert message when editing the grid without selecting any rows.

C:\Users\Manisankar.durai\Desktop\sshot-3.png

Figure 3: Normal Editing in grid and also disables the remaining items in dropdown which are not necessary to show.


Conclusion

I hope you enjoyed learning about how to show DropDown with CRUD action list in JavaScript Grid.

You can refer to our JavaScript Grid feature tour 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