[英]How to pass data to _Layout.cshtml
在所有頁面使用的_Layout.cshtml中,選擇任何背景圖像時,我都想顯示所選的圖片。 但是,不幸的是,我不知道如何將這些數據傳遞給_Layout.cshtml。
AT _Layout.cshtml
<style type="text/css">
#body-bg {
background-image: url('//I want to change here');
}
</style>
我應該怎么做? 從任何控制器,此數據應傳遞到_Layout.cshtml,但如何?
最可靠的方法是使用基本的viewmodel類,並放置一個字符串屬性來保存圖像路徑:
型號類別
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
之外使用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
。
參考文獻:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.