【发布时间】:2015-06-16 21:40:30
【问题描述】:
我想根据用户选择的主题来设置我的 jumbotron 的样式。我想使用 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>
}
}
jumbotron 的主题和样式应取决于用户的选择。
【问题讨论】:
-
如果你愿意使用JQuery,你可以使用$('#selector').addClass()。
-
为了减少比较开销,我会为主题添加一个枚举:示例
if(theme.ThemeType == Themes.ThemeTypes.beach) { \\Do Work }这样您比较的值要小得多。对于您的问题,尽管我建议您使用 jQuery,如果可以的话,它是 addClass 函数。否则,在您的 cshtml 文件中,您可以使用“@”符号插入 c# 逻辑。 Here is another question that uses it -
为了简单和模块化,还可以考虑使用 Html.RenderAction() 或 Html.Partial()
标签: c# html css asp.net asp.net-mvc