最稳健的方法是使用基本视图模型类并放置一个字符串属性来保存图像路径:
模型类
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>
如果您使用相对路径(例如 ~/Images/Selected.png)而不是绝对路径来引用图像路径,请使用带有字符串属性的 UrlHelper.Content 作为参数:
#body-bg {
background-image: url('@Url.Content(Model.BackgroundImage)');
}
别忘了在控制器动作方法中设置viewmodel的字符串属性:
public class HomeController : Controller
{
// other stuff
return View(new BaseViewModel { BackgroundImage = "/path/to/image.png" });
}
注意:除了视图模型之外,您还可以使用 ViewBag 或 ViewData(它们都会自动传递给视图),方法是将 Model 更改为 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();
}
注意ViewBag 是动态的,可能需要额外检查以防止在使用ViewBag 属性时抛出NullReferenceException。
参考资料:
Passing Data to Views (MS Documentation)
Pass data to layout that are common to all pages
Passing Data to a Layout Page