我可以将 ViewBag 从控制器发送到 MVC 中的另一个控制器吗?

Can I send ViewBag from controller to anther Controller in MVC?

我有一个名为 GetPrivlidge() 的方法,我将在每个控制器中使用它,此方法用于当前登录用户将看到什么,什么不会看到,这是方法

 public void GetPrivlidge()
 {
        string name = System.Web.HttpContext.Current.User.Identity.Name;
        name = EncriptionAndDecription.Encrypt(name);
        int UserId = (from c in db.users where c.Arabicusername == name select c.Usersid).SingleOrDefault();
        SamahyatOfUser S = (from SS in db.SamahyatOfUsers where SS.User_Id == UserId select SS).SingleOrDefault();
        ViewBag.Pri = S;
        string RoleName = (from R in db.Roles where R.User_ID == UserId && R.UserName == name select R.RoleName).SingleOrDefault();
        if (RoleName.Equals(EncriptionAndDecription.Encrypt("Admin")))
        {
            ViewBag.ADMIN = true;
        }
        else
        {
            ViewBag.ADMIN = false;
        }
 }

我使用 ViewBag.Pri 检查特权布局,我必须在每个操作中发送这个 ViewBag 所以我决定制作具有所有常用方法的控制器这是我的控制器

 public class AllRequiredDataController : Controller
 {
    //
    // GET: /AllRequiredData/
    mts_exchangeEntities db = new mts_exchangeEntities();
    //this Method is used in privlidge that make user do thing and dont make anthor thing (Do or not Do)
    #region privlidge_Data
    public void GetPrivlidge()
    {
        string name = System.Web.HttpContext.Current.User.Identity.Name;
        name = EncriptionAndDecription.Encrypt(name);
        int UserId = (from c in db.users where c.Arabicusername == name select c.Usersid).SingleOrDefault();
        SamahyatOfUser S = (from SS in db.SamahyatOfUsers where SS.User_Id == UserId select SS).SingleOrDefault();
        ViewBag.Pri = S;
        string RoleName = (from R in db.Roles where R.User_ID == UserId && R.UserName == name select R.RoleName).SingleOrDefault();
        if (RoleName.Equals(EncriptionAndDecription.Encrypt("Admin")))
        {
            ViewBag.ADMIN = true;
        }
        else
        {
            ViewBag.ADMIN = false;
        }
    }
    #endregion
}

_layOut 中,我接受这个 ViewBag 并为 in 进行转换并像这样

一样享有特权
FinalMts.Models.SamahyatOfUser S = (FinalMts.Models.SamahyatOfUser)ViewBag.Pri; 

并在操作中创建 Controller 对象并调用方法 GetPrivlidge() 因为这个

 AllRequiredDataController Required = new AllRequiredDataController();
    public ActionResult AddCurrencyPrices()
    {
        //get privlidg Data
        Required.GetPrivlidge();
        return View();
    }

但是 layout 看不到 ViewBag.Pri 并且错误消息说

Object reference not set to an instance of an object.

这个控制器是否看不到 ViewBag 如果是,我应该如何处理这个 ViewBag

每个控制器都有自己的 ViewBag。更好的是继承你的控制器形式 AllRequiredDataController 并使用这种方式

class Controller1 : AllRequiredDataController
{
    public ActionResult AddCurrencyPrices()
    {
        //get privlidg Data
        GetPrivlidge();
        return View();
    }
}