Asp.Net MVC Core 2 - 在_Layout上使用ViewBag

时间:2018-03-07 11:49:29

标签: c# asp.net-mvc asp.net-core-mvc

我想在视图包上动态设置一些属性,例如RootCSSUrl,并在_Layout.cshtml页面上阅读。

到目前为止,我尝试使用“BaseController”(并且所有控制器都继承自它)并在构造函数上将这些属性设置为ViewBag.RootCSSUrl = isDevelopment ? "blob.mysite.com":"blob.mysite.com";

问题是在_layout渲染上,此值始终为null ...

我做错了什么?

1 个答案:

答案 0 :(得分:1)

我设法通过创建https://damienbod.com/2015/09/15/asp-net-5-action-filters/

中的全局操作过滤器来实现

actionFilter代码非常简单:

public class CommonViewBagInitializerActionFilter : ActionFilterAttribute
{
    public override void OnResultExecuting(ResultExecutingContext context)
    {
#if DEBUG
        ((BaseController)context.Controller).ViewBag.RootBlobURL = "";
#else
        ((Controller)context.Controller).ViewBag.RootBlobURL = "https://blob.mysite.com";
#endif
    }
}

过滤器的注册是:

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc(config =>
        {
            config.Filters.Add(new CommonViewBagInitializerActionFilter());
        });
    }