我是否可以不再将ViewData传递给MVC Core 1.0中的_Layout.cshtml?

时间:2016-08-06 14:27:04

标签: asp.net-mvc razor asp.net-core

我正在尝试将背景图片的网址传递给我的_Layout.cshtml

public HomeController()
{
    this.ViewData["BackgroundImage"] = "1920w/Stipula_fountain_pen.jpg";
}

<body style="background-image: url(@(string.Format("assets/images/{0}", ViewData["BackgroundImage"])))">
    ...
</body>

ViewData内的_Layout.cshtml始终为空。这是否按预期工作?我宁愿不要走BaseViewModel/BaseController路线,因为感觉有点矫枉过正。

编辑:似乎实际上没有使用构造函数中设置的ViewData,因为一旦执行了一个动作,该集合就是空的。如果我在操作中设置ViewData,那么该数据会传递给_Layout.cshtml - 对我来说感觉就像是一个错误。

2 个答案:

答案 0 :(得分:4)

您可以使用操作过滤器为所有控制器操作设置ViewData

public class SetBackgroundUrlAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        base.OnActionExecuted(filterContext);
        var result = filterContext.Result as ViewResult;
        if (result != null)
        {
            result.ViewData["BackgroundImage"] = "1920w/Stipula_fountain_pen.jpg";
        }
    }
}

[SetBackgroundUrl]
public HomeController()
{

}

或者只是覆盖控制器的OnActionExecuted方法:

    public override void OnActionExecuted(ActionExecutedContext context)
    {
        base.OnActionExecuted(context);
        var result = context.Result as ViewResult;
        if (result != null)
        {
            result.ViewData["BackgroundImage"] = "1920w/Stipula_fountain_pen.jpg";
        }
    }

答案 1 :(得分:1)

根据adem caglin的答案进行扩展我使用了此过滤器属性,该属性可以采用任意网址:

[AttributeUsage(AttributeTargets.Class|AttributeTargets.Method, AllowMultiple = false)]
public class SetBackgroundUrlAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        base.OnActionExecuted(filterContext);

        if (!string.IsNullOrWhiteSpace(this.Url))
        {
            var result = filterContext.Result as ViewResult;

            if (result != null)
                result.ViewData["BackgroundImage"] = this.Url;
        }
    }

    public string Url { get; set; }
}

并且像这样使用:

[SetBackgroundUrl(Url = "1920w/Stipula_fountain_pen.jpg")]
public class HomeController : Controller
{
    ...
}