如何在不使用控制器基类的情况下为所有视图设置 ViewBag 属性? [英] How to set ViewBag properties for all Views without using a base class for Controllers?

查看:29
本文介绍了如何在不使用控制器基类的情况下为所有视图设置 ViewBag 属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

过去,我通过让所有控制器继承自一个公共基本控制器,以全局方式将公共属性(例如当前用户)粘贴到 ViewData/ViewBag 上.

In the past I've stuck common properties, such as the current user, onto ViewData/ViewBag in a global fashion by having all Controllers inherit from a common base controller.

这使我可以在基本控制器上使用 IoC,而不仅仅是针对此类数据访问全局共享.

This allowed my to use IoC on the base controller and not just reach out into global shared for such data.

我想知道是否有其他方法可以将这种代码插入到 MVC 管道中?

I'm wondering if there is an alternate way of inserting this kind of code into the MVC pipeline?

推荐答案

我没有尝试过,但你可以看看 注册您的视图,然后在激活过程中设置视图数据.

Un-tried by me, but you might look at registering your views and then setting the view data during the activation process.

因为视图是即时注册的,注册语法不能帮助你连接到 Activated 事件,所以你需要在 Module 中设置它:

Because views are registered on-the-fly, the registration syntax doesn't help you with connecting to the Activated event, so you'd need to set it up in a Module:

class SetViewBagItemsModule : Module
{
    protected override void AttachToComponentRegistration(
        IComponentRegistration registration,
        IComponentRegistry registry)
    {
        if (typeof(WebViewPage).IsAssignableFrom(registration.Activator.LimitType))
        {
            registration.Activated += (s, e) => {
                ((WebViewPage)e.Instance).ViewBag.Global = "global";
            };
        }
    }
}

这可能是我提出的唯一的工具是锤子"类型的建议之一;可能有更简单的启用 MVC 的方法来实现它.

This might be one of those "only tool's a hammer"-type suggestions from me; there may be simpler MVC-enabled ways to get at it.

另一种代码更少的方法 - 只需附加到控制器

Alternate, less code approach - just attach to the Controller

public class SetViewBagItemsModule: Module
{
    protected override void AttachToComponentRegistration(IComponentRegistry cr,
                                                      IComponentRegistration reg)
    {
        Type limitType = reg.Activator.LimitType;
        if (typeof(Controller).IsAssignableFrom(limitType))
        {
            registration.Activated += (s, e) =>
            {
                dynamic viewBag = ((Controller)e.Instance).ViewBag;
                viewBag.Config = e.Context.Resolve<Config>();
                viewBag.Identity = e.Context.Resolve<IIdentity>();
            };
        }
    }
}

编辑 2:另一种直接从控制器注册代码工作的方法:

Edit 2: Another approach that works directly from the controller registration code:

builder.RegisterControllers(asm)
    .OnActivated(e => {
        dynamic viewBag = ((Controller)e.Instance).ViewBag;
        viewBag.Config = e.Context.Resolve<Config>();
        viewBag.Identity = e.Context.Resolve<IIdentity>();
    });

这篇关于如何在不使用控制器基类的情况下为所有视图设置 ViewBag 属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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