亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Asp .Net Core 在數據庫檢查布局上隱藏菜單

Asp .Net Core 在數據庫檢查布局上隱藏菜單

C#
達令說 2023-04-29 16:51:04
我需要根據數據庫檢查在側邊欄菜單中隱藏和顯示一些鏈接,但由于布局沒有頁面模型,我該如何實現呢?如果完成索賠很容易,但我需要訪問數據庫@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>}  
查看完整描述

2 回答

?
弒天下

TA貢獻1818條經驗 獲得超8個贊

由于您正在嘗試在布局(不包含模型)中執行數據庫操作,因此依賴注入可以幫助您。

您可以定義一個具有 DB 訪問方法的類,將其注冊到您的服務,并從任何 View/Controller/pageModel 輕松使用它的方法

我將用代碼解釋:

這是我們的依賴:

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();

? ? }

}

將其注冊到您的服務中Startup(您的依賴項應在注冊 DBContext 后注冊)


public void ConfigureServices(IServiceCollection services)

{

? ? // Some code here


? ? services.AddDbContext<DBContext>(options =>

? ? ? ? options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));


? ? services.AddScoped<MyDependency>();

}

然后在你的布局中:


@inject MyDependency MyDependency


@if(MyDependency.CheckInDb())

{

? ? // Do something

}?

else

{

? ? // Do something else

}


查看完整回答
反對 回復 2023-04-29
?
犯罪嫌疑人X

TA貢獻2080條經驗 獲得超4個贊

您可以使用視圖模型或 HttpContext



查看完整回答
反對 回復 2023-04-29
  • 2 回答
  • 0 關注
  • 151 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號