Hi ,
can anyone suggest with sample code to bind fmenu from myslq db in _Layout.cshtml . ?
sample code is vital for implement.
Thanks in advance
Karthik.k
Hi ,
can anyone suggest with sample code to bind fmenu from myslq db in _Layout.cshtml . ?
sample code is vital for implement.
Thanks in advance
Karthik.k
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Sandhiya PriyaRank #26 · 43.2K reputationPosted Jan 2, 2026, 5:57 AM EST
binding a dynamic menu from a MySQL database into your
_Layout.cshtmlin ASP.NET Core MVC is a common requirement. Let me walk you through a step-by-step example with code.Steps to Bind Menu from MySQL DB
1. Create a Menu Model
public class MenuItem { public int Id { get; set; } public string Title { get; set; } public string Url { get; set; } }2. Setup EF Core with MySQL
Install the NuGet package:
Configure
DbContext:public class AppDbContext : DbContext { public AppDbContext(DbContextOptions options) : base(options) { } public DbSet MenuItems { get; set; } }In
Program.cs(orStartup.cs):builder.Services.AddDbContext(options => options.UseMySql(builder.Configuration.GetConnectionString("DefaultConnection"), new MySqlServerVersion(new Version(8, 0, 25))));3. Create a Service to Fetch Menu
public interface IMenuService { Task> GetMenuAsync(); } public class MenuService : IMenuService { private readonly AppDbContext _context; public MenuService(AppDbContext context) { _context = context; } public async Task> GetMenuAsync() { return await _context.MenuItems.ToListAsync(); } }Register service in
Program.cs:4. Use ViewComponent for Menu
Create
MenuViewComponent.cs:public class MenuViewComponent : ViewComponent { private readonly IMenuService _menuService; public MenuViewComponent(IMenuService menuService) { _menuService = menuService; } public async Task InvokeAsync() { var menuItems = await _menuService.GetMenuAsync(); return View(menuItems); } }5. Create View for Menu Component
Views/Shared/Components/Menu/Default.cshtml:6. Call Component in
_Layout.cshtmlResult
Menu items are fetched from MySQL DB.
They are rendered dynamically in
_Layout.cshtml.Easy to maintain: just update the DB table, and the menu updates automatically.