问题
Is there a Way to Create a Global ViewBag that can be used in Different Views.
In my application's scenario,
1)I have used a DropDown for Company that is used into _Layout.cshtml page.
2) For that Dropdown I am passing the Value by making ViewBag.Company in each action.
I want the solution::
1) A Global ViewBag.Company having List that we are passing from each action.
2) Then there won't be any need to create ViewBag.Company in each Action.
This question might be something different. But How can we achieve this?
回答1:
In real world you have mistake in your architecture.
public class CustomNameAttribute : ActionFilterAttribute
{
public void OnResultExecuting(ResultExecutingContext filterContext)
{
filterContext.Controller.ViewBag.Company = "Company";
}
}
I think you need use Authorization and use property User
回答2:
Add a global filter that adds the Company to the view bag.
Basically create an actionfilter:
public class CompanyFilter : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
filterContext.Controller.ViewBag.Company = "MyCompany";
}
}
And register it globally
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new CompanyFilter()); // Add this line
filters.Add(new HandleErrorAttribute());
}
}
来源:https://stackoverflow.com/questions/23381295/make-a-global-viewbag