Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I no longer pass ViewData to _Layout.cshtml in MVC Core 1.0?

I'm trying to pass a URL for a background image to my _Layout.cshtml,

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

and

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

but ViewData is always empty inside _Layout.cshtml. Is that working as intended? I'd rather not go down the BaseViewModel/BaseController route as that feels like overkill.

EDIT: It seems as if ViewData set in the constructor isn't actually used, because once an action is executing the collection is empty. If I set ViewData inside the action then that data is passed on to _Layout.cshtml - feels like a bug to me.

like image 818
Thorsten Westheider Avatar asked Dec 06 '25 06:12

Thorsten Westheider


1 Answers

You can use an action filter to set ViewData for all controller actions:

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()
{

}

Or just override OnActionExecuted method of the controller:

    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";
        }
    }
like image 120
adem caglin Avatar answered Dec 07 '25 23:12

adem caglin