如何根据用户输入mvc5设置<div>标签的样式

时间:2015-06-16 21:40:31

标签: c# html css asp.net asp.net-mvc

我想根据用户选择的主题来设计我的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的主题和样式应取决于用户选择的内容。

1 个答案:

答案 0 :(得分:0)

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

您可以在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是可选的。