[英]How to style a <div> tag according to user input mvc5
我想根據用戶選擇的主題來設計我的超大屏幕。 我想使用if語句,但是我不知道在CSHTML中執行此操作的正確方法。
我知道以下代碼不正確,任何人都可以幫助我展示如何執行此操作嗎?
這是我的代碼:
themes = db.Themes.ToList();
foreach (var item in themes)
{
if (item.themeImage != null)
{
string imageBase = Convert.ToBase64String(item.themeImage);
imageSource1 = string.Format("data:image/gif;base64,{0}", imageBase);
}
if (theme == beach && item.themeID == 1)
{
<text>
<div class="jumbotron" id="@item.themeID" img src="@item.themeImage">
</text>
}
else if (theme == animals && item.themeID == 2)
{
<text>
<div class="jumbotron" id="@item.themeID" style="background-image:@imageSource1; background-size:cover">
</text>
}
else if (theme == kitchen && item.themeID == 3)
{
<text>
<div class="jumbotron" id="@item.themeID" style="background-image:@imageSource1; background-size:cover">
</text>
}
}
巨無霸的主題和樣式應取決於用戶選擇的內容。
您可以創建一個小函數,然后調用該函數以獲得正確的樣式。
您可以在cshtml中做到這一點
@{
string GetStylePerTheme(int themeId)
{
switch(themeId)
{
case 1:
return "color: red;";
case 2:
return "color: blue;";
default:
return "color: black;";
}
}
}
並將其用於html(與cshtml相同)
<text>
<div class="jumbotron" id="@item.themeID" style="@GetStylePerTheme(item.themeID)">
</text>
現在,如果您希望它在多個頁面上都是干凈的並可重用的,請創建一個自定義幫助器(一種簡單的靜態方法,實用)
public static string GetStylePerTheme(this HtmlHelper helper, int themeId) { switch(themeId) { case 1: return "color: red;"; case 2: return "color: blue;"; default: return "color: black;"; } }
對於cshtml
<text>
<div class="jumbotron" id="@item.themeID" style="@Html.GetStylePerTheme(item.themeID)">
</text>
擴展HtmlHelper是可選的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.