Setting every page's background is rather simple in ASP.Net WebForms where you have access to the Page_Load event in the code-behind of a MasterPage but how is this best done in MVC? After spending several hours researching various alternatives I chose to assign the value to the ViewBag through a "base" controller, derive subsequent controllers from that base and then access that value in _Layout.cshtml.

Here is the base controller, in which I assign a url that points to a specific image:

public class BaseController : Controller
{
    public BaseController()
    {
        ViewBag.url = BingImageLoader.getBingImageUrl();    
    }
}

The next step is to derive subsequent controllers, in this case the HomeController from that base class:

public class HomeController : BaseController
{
    public ActionResult Index()
    {
        return View();
    }
    .
    .

And finally, use the ViewBag in the head element of _Layout.cshtml to set the background-image style property.

    .
    .   
    <style type="text/css">
        body {
            background-image: url(@ViewBag.url);  
            background-repeat: no-repeat;
            background-size: cover;
        }
    </style>
</head>

This did accomplish what I set out to do; however, along the way there were a number of alternatives indicated, including using ActionFilters. To be honest, creating a CustomActionFilter and using ActionFilterAttributes and overriding OnActionExecuting seems like overkill but sometimes the simplest way is not always the best.

Ultimately, the question comes down to "Is there a better way?" Are there side-effects from introducing an intermediary? If I override my ViewBag.url in the individual controller methods, the image changes accordingly. So I have yet to find any problems but there may be other issues resulting from this approach.

So again, "Is there a better way"?

Related posts

Recent Viewed