Articles in this section
Category / Section

How render ejmenu in the Grid's column like a dropdown?

1 min read

This knowledge base explains the way to render menu in the Grid columns.

Usually, Grid provides an option to render any control in its columns using template feature along with the templateRefresh event. Likewise, an icon has been rendered in the template column, with click event to handle the context menu (or ejMenu).

Render the Grid with custom contextmenu items and events such as templateRefresh, contextClick and contextOpen.

 

HTML

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

 

JS

<script type="text/javascript">
    $(function () {
        $("#Grid").ejGrid({
            dataSource: window.gridData,
            allowPaging: true,
            editSettings: {allowAdding: true },
            toolbarSettings: { showToolbar: true, toolbarItems: [ej.Grid.ToolBarItems.Add, ej.Grid.ToolBarItems.Update] },
            contextMenuSettings: {
                enableContextMenu: true,
                //disabled the default items
                disableDefaultItems: true,
                //add custom items
                customContextMenuItems: [
                    { id: 'View_Record', text: "View Record" },
                    { id: 'Item_Add', text: "Add Item" }
                ]
            },
            columns: [
                    { field: "OrderID", isPrimaryKey: true, headerText: "Order ID" },
                    { field: "CustomerID", headerText: "Customer ID" },
                    { field: "EmployeeID", headerText: "Employee ID" },
                    { field: "Freight", format: "{0:C2}" },
                    {  template: "#template", width: 30 },
 
            ],
            templateRefresh: "refreshTemplate",
            //prevent the default context mention
            contextOpen: "contextOpen",
            contextClick: "contextClick"
 
        });
    });
</script>

 

RAZOR:

@(Html.EJ().Grid<object>("Grid")
      .Datasource((IEnumerable<object>)ViewBag.datasource)
      .AllowPaging()
      .EditSettings(edit => edit.AllowAdding())
      .ToolbarSettings(tool => tool.ShowToolbar()
          .ToolbarItems(tools =>
          {
              tools.AddTool(ToolBarItems.Add);
              tools.AddTool(ToolBarItems.Update);
          }))
       .ContextMenuSettings(con=>con.EnableContextMenu(true).DisableDefaultItems(true)
           .CustomContextMenuItems(menu=>{
               menu.AddItem("View_Record", "View Record");
               menu.AddItem("Item_Add", "Add Item");
            })
       )
      .Columns(col =>
          {
              col.Field("OrderID").HeaderText("Order ID").IsPrimaryKey(true).Add();
              col.Field("CustomerID").HeaderText("Customer ID").Add();
              col.Field("EmployeeID").HeaderText("Employee ID").Add();
              col.Field("Freight").Format("{0:C2}").Add();
              col.Template("#template").Width(50).Add();
          })
        .ClientSideEvents(events => {
            events.TemplateRefresh("refreshTemplate");
            events.ContextClick("contextClick");
            events.ContextOpen("contextOpen");
        })
)

 

C#

namespace Sample.Controllers
{
    public class GridController : Controller
    {
        public ActionResult GridFeatures()
        {
            ViewBag.datasource = new NorthwindDataContext().OrdersViews.ToList();
            return View();
        }
    }
}

 

ASPX

    <ej:Grid id="Grid" runat="server" AllowPaging="true" ClientIDMode="Static">
        <ContextMenuSettings EnableContextMenu="true" DisableDefaultItems="true">
                    <CustomContextMenuItem>
                        <ej:CustomContexMenuItems Id="View_Record" Text="View Record" /> 
                        <ej:CustomContexMenuItems Id="Item_Add" Text="Add Item" /> 
                    </CustomContextMenuItem>
        </ContextMenuSettings>
        <EditSettings AllowAdding="true" ></EditSettings>
        <ToolbarSettings ShowToolbar="true" ToolbarItems="add,update"></ToolbarSettings>
        <Columns>
            <ej:Column Field="OrderID" HeaderText="Order ID" IsPrimaryKey="true"/>
            <ej:Column Field="CustomerID" HeaderText="Customer ID" />
            <ej:Column Field="EmployeeID" HeaderText="Employee ID" />
            <ej:Column Field="Freight" HeaderText="Freight" Format="{0:C2}" />
            <ej:Column Template="#template" Width="50"></ej:Column>
        </Columns>
        <ClientSideEvents TemplateRefresh="refreshTemplate" ContextClick="contextClick" ContextOpen="contextOpen"  />
    </ej:Grid>

 

namespace sqlbinding
{
    public partial class _Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            this.Grid.DataSource = order;
            this.Grid.DataBind();
        }
    }
}

 

.Net Core

@using Syncfusion.JavaScript.Models;
 
@{
    var custom = new List<CustomContextMenuItems>()
    {
        new CustomContextMenuItems(){ Id="View_Record", Text="View Record" },
        new CustomContextMenuItems(){ Id="Item_Add", Text="Add Item" }
    };
}
<ej-grid id="Grid" allow-paging="true" datasource="ViewBag.dataSource"
         template-refresh="refreshTemplate" context-click="contextClick" context-open="contextOpen">
    <e-context-menu-settings enable-context-menu="true" disable-default-items="true" custom-context-menu-items="custom" />
    <e-edit-settings allow-adding="true"></e-edit-settings>
    <e-toolbar-settings show-toolbar="true" toolbar-items="@(new List<string>() {"add","update"})"></e-toolbar-settings>
    <e-columns>
        <e-column field="OrderID" header-text="Order ID" is-primary-key="true"></e-column>
        <e-column field="CustomerID" header-text="Customer ID"></e-column>
        <e-column field="EmployeeID" header-text="Employee ID"></e-column>
        <e-column field="Frieght" format="{0:C2}"></e-column>
        <e-column template="#template" width="50"></e-column>
    </e-columns>
</ej-grid>

 

namespace core1.Controllers
{
    public partial class GridController : Controller
    {
        public static List<Orders> order = new List<Orders>();
        public ActionResult GridFeatures()
        {
            ViewBag.dataSource = order;
            return View();
        }
    }
}
 

 

Angular2:

<ej-grid id="Grid" #grid  [allowPaging]="true"
         [dataSource]="datasrc" (templateRefresh)="refreshTemplate($event)" 
         (contextClick)="contextClick($event)" (contextOpen)="contextOpen($event)"
         [contextMenuSettings]="context"
         [toolbarSettings]="toolbarSettings" 
         >
    <e-columns>
        <e-column field="OrderID" headerText="Order ID"></e-column>
        <e-column field="CustomerID" headerText="Customer ID" ></e-column>
        <e-column field="EmployeeID" headerText="Employee Name"></e-column>
        <e-column field="Freight" format="{0:C2}"></e-column>
        <e-column width="50">
            <ng-template e-template let-data>
                <div class="ejclick e-icon e-custom-menu"></div>
            </ng-template>
        </e-column>
    </e-columns>
</ej-grid>

 

TypeScript:

import { Component, OnInit, Input, ElementRef, ViewChild } from '@angular/core';
import { EJComponents } from "ej-angular2/src/ej/core";
 
@Component({
    selector: 'ej-app',
    templateUrl: 'src/grid/grid.component.html',
})
export class GridComponent {
    constructor() {
        this.context = {
            enableContextMenu: true,
            //disabled the default items
            disableDefaultItems: true,
            //add custom items
            customContextMenuItems: [
                { id: 'View_Record', text: "View Record" },
                { id: 'Item_Add', text: "Add Item" },
            ]
        };
        this.datasrc = data;
        this.editSettings = { allowAdding: true };
        this.toolbarSettings = {
            showToolbar: true,
            toolbarItems: ["add", "update"]
        };
    }
    public datasrc: any;
    public context: any;
    public editSettings: any;
    public toolbarSettings: any;
 
}
 

 

Define the template for the columns and required CSS references.

 
<script id="template" type="text/x-jsrender">
    <div class=".ejclick e-icon e-custom-menu"></div>
</script>
 

 

 
<style>
    .e-custom-menu:before {
        content: "\e673";
    }
</style>
 

 

Bind the click event to the template element in the templateRefresh event of the Grid which will programmatically show the context menu after clicking them. Later, contextOpen event will be defined to prevent the default behavior of the context menu whereas the contextClick will adds the functionality to the custom context menu items.

<script type="text/javascript">
  var target = null;
    //Trigger Context menu using the showContextMenu Method
    function refreshTemplate(args) {
        $(args.cell).on("click", ".ejclick", $.proxy(function (e) {
            var obj = $("#" + this.element.attr("id") + "_Context").ejMenu("instance");
            e.type = "mouseup";
            e.which = 3;
            target = $(e.currentTarget).closest("tr").find(".e-rowcell:not('.e-templatecell')")[0];
            obj.showContextMenu(null, null, target, e, true)
        },this));
    }
 
    /*Prevents default functionality of the Context Menu Grid,
    menu opened only for the template element*/
    function contextOpen(args) {
        if (!$(args.events.target).hasClass("e-custom-menu"))
            args.cancel = true;
    }
 
    function contextClick(args) {
        if (args.text == "View Record")
            alert(JSON.stringify(this.model.currentViewData[this.getIndexByRow($(target).closest("tr"))]));
        else this.addRecord();
    }
</script>

 

TypeScript:

import { Component, OnInit, Input, ElementRef, ViewChild } from '@angular/core';
import { EJComponents } from "ej-angular2/src/ej/core";
 
@Component({
    selector: 'ej-app',
    templateUrl: 'src/grid/grid.component.html',
})
export class GridComponent {
    constructor() {
    }
 
    @ViewChild('grid') Grid: EJComponents<any, any>;//
 
    public target: any;
 
    refreshTemplate(event: any) {
        $(event.cell).on("click", ".ejclick", $.proxy(function (e) {
            var obj = $("#" + this.Grid.widget.element.attr("id") + "_Context").ejMenu("instance");
            e.type = "mouseup";
            e.which = 3;
            this.target = $(e.currentTarget).closest("tr").find(".e-rowcell:not('.e-templatecell')")[0];
            obj.showContextMenu(null, null, this.target, e, true)
        }, this))
    }
 
 
    /*Prevents default functionality of the Context Menu Grid,
     menu opened only for the template element*/
    contextOpen(args) {
        if (!$(args.events.target).hasClass("e-custom-menu"))
            args.cancel = true;
    }
 
    contextClick(args) {
        if (args.text == "View Record")
            alert(JSON.stringify(this.Grid.widget.model.currentViewData[this.Grid.widget.getIndexByRow($(this.target).closest("tr"))]));
        else this.Grid.widget.addRecord();
    }
 
}
 

 

Figure: Grid with custom context menu opened from the template column click

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