Open and close ContextMenu

21 Apr 20222 minutes to read

ContextMenu can be opened and closed programmatically whenever required by using the open and close methods.

In the following example, the ContextMenu is opened using the open method at the specified position using top and left. Also, ContextMenu is closed using close method on ContextMenu item click or document click.

@Html.EJS().Button("button").Content("Open ContextMenu").Render()
@Html.EJS().ContextMenu("contextmenu").Items((IEnumerable<object>)ViewBag.menuItems).Render()

<script>
        document.addEventListener("DOMContentLoaded", function () {
            document.getElementById('button').onclick = function () {
                ej.base.getComponent(document.getElementById("contextmenu"), "contextmenu").open(60, 20);
            }
        });

    </script>

    <style>

        button {
            margin: 20px 0 0 5px;
        }
    </style>

</style>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace WebApplication1.Controllers
{
    public class ContextMenuController : Controller
    {
        public ActionResult OpenClose()
        {
            List<object> menuItems = new List<object>();
            menuItems.Add(new
            {
                text = "Cut"
            });
            menuItems.Add(new
            {
                text = "Copy"
            });
            menuItems.Add(new
            {
                text = "Paste"
            });
            ViewBag.menuItems = menuItems;
            return View();
        }
    }
}