Articles in this section
Category / Section

How to invoke a controller method based on each menu item click in Blazor?

1 min read

This article explains how to invoke a controller method based on each menu item click to its respective action methods in Blazor Context menu.

 

Create a controller class with methods for each menu action.

 
namespace BlazorApp.Controllers
{
    [Route("[controller]/[action]")]
    public class HomeController : Controller
    {
      public void Save()
        {
          Console.WriteLine("save is clicked");
        }
    }
}
 

 

Ensure, AddControllers an MapControllers called in Program.cs file.

 
using Syncfusion.Blazor;
 
var builder = WebApplication.CreateBuilder(args);
 
// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor(); 
builder.Services.AddSyncfusionBlazor();
builder.Services.AddControllers();
builder.Services.AddSingleton<WeatherForecastService>();
 
var app = builder.Build();
 
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}
 
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.MapControllers();
app.MapBlazorHub();
app.MapFallbackToPage("/_Host");
app.Run();

 

 

Inject NavigationManager in Index.razor file. In the ItemSelected event of Menu, controller method called using NavigationManager.

Index.razor

inject NavigationManager NavigationManager
 
<SfMenu TValue="MenuItem">
    <MenuItems>
       <MenuItem Text="File" IconCss="e-icons e-file">
            <MenuItems>
                <MenuItem Text="Open" IconCss="e-icons e-open"></MenuItem>
                <MenuItem Text="Save" IconCss="e-icons e-save"></MenuItem>
                <MenuItem Separator="true"></MenuItem>
                <MenuItem Text="Exit"></MenuItem>
            </MenuItems>
        </MenuItem>
       <MenuItem Text="Help"></MenuItem>
    </MenuItems>
    <MenuEvents TValue="MenuItem" ItemSelected="Open" ></MenuEvents>
</SfMenu>
@code {
  
    public void Open()
    {
       NavigationManager.NavigateTo($"Home/Save",
                    forceLoad: true);
    }
}

 

View Sample in GitHub

Refer to our documentation and online samples for more features. If you have any queries, please let us know in the comments below. You can also contact us through our Support forum or Support ticket. We are happy to assist you!

 

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please  to leave a comment
Access denied
Access denied