Search code examples
c#asp.net-core-2.2

Asp .Net Core hide menu on layout on database check


I need to hide and show some links in a sidebar menu according to a database check but since layout has no page model, how can i achieve this? It's easy if it's done with claims but i need to hit the database

@if (User.Identity.IsAuthenticated)
{
    <li class="nav-item has-treeview">

        <a asp-page="/Account/Documentos/Index" class="nav-link custom-sidebar-link">
            <i class="nav-icon fas fa-file-alt"></i>
            <p class="text-white">
                Documentos
            </p>
        </a>

    </li>
    // need to hide this on database check
    <li class="nav-item has-treeview">

        <a asp-page="/Account/Consumos/Index" class="nav-link custom-sidebar-link">
            <i class="nav-icon fas fa-cogs"></i>
            <p class="text-white">
                Arranque Produção
            </p>
        </a>

    </li>
}  

Solution

  • Since you're trying to do DB operations in a layout (which doesn't contain a model), Dependency Injection can help you.

    You can define a class that have methods with DB access, register it to your services, and use it's methods easily from any View/Controller/pageModel

    I'll explain with a code:

    Here's our dependency:

    public class MyDependency 
    {
        // You can use dependency injection in a chained fashion, 
        // DBContext is injected in our dependency
        private readonly DBContext _dbContext;
    
        public MyDependency(DBContext dbContext)
        {
            _dbContext = dbContext;
        }
    
        // Define a method that access DB using dbContext
        public bool CheckInDb()
        {
            return dbContext.SomeCheck();
        }
    }
    

    Register it to your services in your Startup (Your dependency should be registered after DBContext has been registered)

    public void ConfigureServices(IServiceCollection services)
    {
        // Some code here
    
        services.AddDbContext<DBContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
    
        services.AddScoped<MyDependency>();
    }
    

    Then in your layout:

    @inject MyDependency MyDependency
    
    @if(MyDependency.CheckInDb())
    {
        // Do something
    } 
    else
    {
        // Do something else
    }