How to invoke a controller method in ASP.NET Core?
This article explains how to invoke a controller method based on each menu item click to its respective action methods in ASP.NET Core Context menu.
Step1: Create a Controller which gets called for each menu item click where the views are returned based on method name.
namespace CoreWebApp.Controllers { public class HomeController : Controller { public IActionResult Index() { return View(); } public IActionResult Open() { return View(); // Triggered for Open click } public IActionResult Save() { return View(); // Triggered for Save click } public IActionResult Exit() { return View(); // Triggered for Exit Click } } }
Step2: Set path to the controller in Startup.cs
app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); });
Step3: Inject the Controller in Index.cshtml and set Url of menu items pointing to controller methods.
@model CoreWebApp.Controllers.HomeController <div class="menu-control"> <ul id="menu"></ul> </div> <script> var menuItems = [ { text: 'File', iconCss: 'em-icons e-file', items: [ { text: 'Open', iconCss: 'em-icons e-open', url: "Home/Open" }, { text: 'Save', iconCss: 'e-icons e-save', url: "Home/Save" }, { separator: true }, { text: 'Exit', url: "Home/Exit" } ] }, { text: 'Help', }, ]; //Menu model definition var menuOptions = { items: menuItems, }; //Menu initialization var menuObj = new ej.navigations.Menu(menuOptions, '#menu'); </script>
Step4: Create views as like in the below example and inject controller in all the pages where controlled method loads this pages as needed.
Open.cshtml
@{ ViewData["Title"] = "Open Page"; } @model CoreWebApp.Controllers.HomeController <h1>Open item is clicked</h1>
Save.cshtml
@{ ViewData["Title"] = "Save Page"; } @model CoreWebApp.Controllers.HomeController <h1>Save item is clicked</h1>
Exit.cshtml
@{ ViewData["Title"] = "Exit Page"; } @model CoreWebApp.Controllers.HomeController <h1>Exit item is clicked</h1>
Now, when user clicks the menu items the pages are loaded via controller.
Conclusion
I hope you enjoyed learning about how to invoke a controller method based on each menu item click to its respective action methods in ASP.NET Core.
You can refer to our ASP.NET Core Menu Bar 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 ASP.NET Core Menu Bar 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 forums, Direct-Trac, or feedback portal. We are always happy to assist you!