根据模型中的值动态更改背景颜色

时间:2014-01-07 10:07:30

标签: css asp.net-mvc-4

我的网页上有以下代码:

@model IEnumerable<LiveTile.Models.MenuItem>

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_LayoutAdmin.cshtml";
}

@foreach (var item in Model) {
    <div class="tile tile-singlewidth">
        <div class="tilecontent tile-singlewidth">
            @Html.DisplayFor(modelItem => item.Name)<p>
            <img src="@Url.Content(item.Url)"  height="30"  alt="Image" title="@Html.DisplayFor(modelItem => item.ActionName)" />
        </div>
    </div>
}

在我的CSS中,我有一个id tile和一个id tile-error。

.tile
{
    float: left;
    margin-right: 10px;
    margin-bottom: 10px;
    height: 75px;
    background-color: #9DB029;
    font-family: "Segoe UI" ,Helvetica,Garuda,Arial,sans-serif;
}

.tile-error
{
    float: left;
    margin-right: 10px;
    margin-bottom: 10px;
    height: 75px;
    background-color: #f00;
    font-family: "Segoe UI" ,Helvetica,Garuda,Arial,sans-serif;
}

现在基于模型中的值,我想将其更改为

任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:0)

我找到了以下解决方案:

@foreach (var item in Model) {

    string cssClass = "tile tile-singlewidth";

    if (item.ControllerName == "red")
    {
        cssClass = "tile-error tile-singlewidth";
    }

    <div class="@cssClass">
        <div class="tilecontent tile-singlewidth">
            @Html.DisplayFor(modelItem => item.Name)<p>
            <img src="@Url.Content(item.Url)"  height="30"  alt="Image" title="@Html.DisplayFor(modelItem => item.ActionName)" />
        </div>
    </div>
}