Asp.net

訪問所有視圖的 Viewbag 屬性

  • September 24, 2021

如何在我的所有視圖中訪問某些 ViewBag 屬性?我希望在任何地方都可以訪問一些資訊,例如目前使用者名等,但不必在我的項目的每個 ActionResult 方法中專門定義屬性

實現您的要求的最好和直接的方法是製作一個自定義基本控制器並從這個基本控制器繼承您的控制器。

public class MyBaseController : Controller
{
   protected override void OnActionExecuting(ActionExecutingContext filterContext)
   {
       ViewBag.someThing = "someThing"; //Add whatever
       base.OnActionExecuting(filterContext);
   }
}

現在不是繼承Controller類,而是繼承MyBaseController你的控制器,如圖所示: -

public class MyOtherController : MyBaseController 
{
   public ActionResult MyOtherAction()
   {
      //Your Stuff
      return View();
   }
   //Other ActionResults
}

引用自:https://stackoverflow.com/questions/27308524