我有一个名为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
并为其制作演员并使用特权
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
,错误消息说
对象引用未设置为对象的实例。
这个控制器看不到ViewBag
如果是,我该怎么办才能处理这个ViewBag
?
答案 0 :(得分:1)
每个控制器都有自己的ViewBag
。更好的方法是继承您的控制器表单AllRequiredDataController
并使用这种方式
class Controller1 : AllRequiredDataController
{
public ActionResult AddCurrencyPrices()
{
//get privlidg Data
GetPrivlidge();
return View();
}
}