如何设置所有视图ViewBag属性,而无需使用基类控制器? [英] How to set ViewBag properties for all Views without using a base class for Controllers?

查看:218
本文介绍了如何设置所有视图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.

我不知道是否有插入这种code进入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.

由于意见上即时登记,登记语法不帮你连接到激活事件,所以你需要将其设置在模块

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.

编辑:的替代,少code做法 - 只是连接到控制器

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:的另一种方法直接从控制器注册code的作品:

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天全站免登陆