【问题标题】:How to style a <div> tag according to user input mvc5如何根据用户输入 mvc5 设置 <div> 标签的样式
【发布时间】: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


【解决方案1】:

您可以创建一个小函数并调用它以获得正确的样式。

你可以在你的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>

现在,如果您希望它干净且可跨多个页面重复使用,请创建一个自定义帮助程序(实际上是一个简单的静态方法)

公共静态字符串 GetStylePerTheme(这个 HtmlHelper 助手,int themeId) { 开关(主题 ID) { 情况1: 返回“颜色:红色;”; 案例2: 返回“颜色:蓝色;”; 默认: 返回“颜色:黑色;”; } }

对于cshtml

<text>
    <div class="jumbotron" id="@item.themeID" style="@Html.GetStylePerTheme(item.themeID)">
</text>

扩展 HtmlHelper 是可选的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-22
    • 2023-01-09
    • 2021-10-13
    • 1970-01-01
    • 2023-02-13
    • 1970-01-01
    • 2012-12-19
    • 1970-01-01
    相关资源
    最近更新 更多