Make a Global ViewBag

余生颓废 提交于 2019-12-11 11:46:37

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!