制作一个全局ViewBag [英] Make a Global ViewBag

查看:172
本文介绍了制作一个全局ViewBag的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种方法可以创建可在不同视图中使用的 Global ViewBag .

在我的应用程序中, 1)我已经使用了 DropDown for Company (用于公司的下拉列表),该页面用于_Layout.cshtml页面.

2)对于该下拉菜单,我通过在每个操作中使用ViewBag.Company来传递值.

我想要解决方案::

1)一家全球性ViewBag.Company,其中包含我们从每个操作传递来的列表.

2)然后,无需在每个操作中创建ViewBag.Company.

这个问题可能有所不同. 但是我们如何实现呢?

解决方案

添加一个将公司添加到视图包的全局过滤器.

基本上创建一个动作过滤器:

public class CompanyFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        filterContext.Controller.ViewBag.Company = "MyCompany";
    }
}

并在全球范围内注册

public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new CompanyFilter()); // Add this line
        filters.Add(new HandleErrorAttribute());
    }
}

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?

解决方案

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());
    }
}

这篇关于制作一个全局ViewBag的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆