The most robust way is using a base viewmodel class and put a string property to hold image path:
Model Class
public class BaseViewModel
{
public string BackgroundImage { get; set; }
}
_Layout.cshtml
@model BaseViewModel
<!DOCTYPE html>
<html>
<head>
<!-- other styles, meta tags, etc. -->
<style type="text/css">
#body-bg {
background-image: url('@Model.BackgroundImage');
}
</head>
<body>
<!-- body part -->
@RenderBody()
</body>
</html>
If you're using relative path (e.g. ~/Images/Selected.png
) instead of absolute path to refer image paths, use UrlHelper.Content
with string property as argument:
#body-bg {
background-image: url('@Url.Content(Model.BackgroundImage)');
}
Also don't forget to set viewmodel's string property inside controller action method:
public class HomeController : Controller
{
// other stuff
return View(new BaseViewModel { BackgroundImage = "/path/to/image.png" });
}
NB: You can use ViewBag
or ViewData
besides a viewmodel (they're both automatically passed to view), by changing Model
to ViewBag
/ViewData
:
// View (CSS)
#body-bg {
background-image: url('@ViewBag.BackgroundImage');
}
// Controller
public class HomeController : Controller
{
// other stuff
ViewBag.BackgroundImage = "/path/to/image.png";
return View();
}
Note that ViewBag
is dynamic, possibly extra check required to prevent NullReferenceException
thrown when using ViewBag
property.
References:
Passing Data to Views (MS Documentation)
Pass data to layout that are common to all pages
Passing Data to a Layout Page