How to open and close ASP.NET MVC Context Menu

28 Aug 20262 minutes to read

The 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 the left and top arguments (open(60, 20)). The ContextMenu closes automatically on 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();
        }
    }
}