How to data bind in ASP.NET MVC Context Menu
28 Aug 20264 minutes to read
To bind a local data source to the ContextMenu, menu items are populated from the data source and mapped to the items property. A parent–child relationship between the items can be established by mapping the id and parentId fields in the data source.
The following example demonstrates how to bind a local data source to the ContextMenu. A separator item is rendered by adding the e-separator class to the corresponding menu item in the beforeItemRender event when the item’s text field is empty.
<div id="contextmenutarget">Right click/Touch hold to open the ContextMenu </div>
@Html.EJS().ContextMenu("contextmenu").Target("#contextmenutarget").Items((IEnumerable<object>)ViewBag.menuItems).BeforeItemRender("beforeItemRender").Render()
<script>
function beforeItemRender(args) {
if (!args.item.text) {
args.element.classList.add('e-separator');
}
}
</script>
<style>
button {
margin: 20px 0 0 5px;
}
#target {
border: 1px dashed;
height: 150px;
padding: 10px;
position: relative;
text-align: justify;
color: gray;
user-select: none;
}
</style>public IActionResult Index()
{
List<object> menuItems = new List<object>();
menuItems.Add(new
{
id=1,
text = "View"
});
menuItems.Add(new
{
id = 2,
text = "Sort By"
});
menuItems.Add(new
{
id = 5,
text = ""
});
menuItems.Add(new
{
id = 3,
text = "New"
});
menuItems.Add(new
{
id = 4,
text = "Ascending",
parentId = 2
});
ViewBag.menuItems = menuItems;
return View();
}