c# - 使用 MVC,如何根据 <td> 之一中包含的日期将 <tr> 格式化为特定类?

标签 c# asp.net-mvc razor view

我有一个显示 Windows 部署进度的 MVC 应用程序。在我看来,我有一个表格显示每个部署的当前状态。其中一个属性是最后一次 checkin 部署的时间(“CurrentTime”)。如果 CurrentTime 超过 4 小时前,我想更改样式。

在我的 MVC View 中,我正在尝试做这样的事情:

@foreach (var item in Model)
{
    if(item.CurrentTime < DateTime.Now.AddHours(-4))
    {
        @:<tr class="warning">
    }
    else
    {
        @:<tr>
    }

这是行不通的。我收到解析器错误:

Encountered end tag "tr" with no matching start tag. Are your start/end tags properly balanced?

有什么简单的方法(我刚刚在学习 MVC/web 编程)来完成这个?

最佳答案

做到这一点的最简单(和更清洁)的方法是做这样的事情:

@foreach (var item in Model)
{
    var warning = item.CurrentTime < DateTime.Now.AddHours(-4) ? "warning" : null;
    <tr class="@warning">
       <td></td>
    </tr>
}

Razor 2+ 的一个不错的功能是,如果值为 null,它将自动删除类属性。此功能称为“条件属性”,如果需要,您可以在此处阅读更多内容。

http://www.davidhayden.me/blog/conditional-attributes-in-razor-view-engine-and-asp.net-mvc-4

关于c# - 使用 MVC,如何根据 <td> 之一中包含的日期将 <tr> 格式化为特定类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29613413/

相关文章:

c# - 为什么 IEnumerable<T> 没有 FindAll 或 RemoveAll 方法?

asp.net - ASP.NET MVC不能与ViewState和Postback一起使用吗?

c# - C# 中的重载解析

c# - 从 Controller 内部的 Action 重定向?

c# - Asp.Net - 如何在母版页中调整 GridView 控件的大小?

c# - 兼容 php、java 和 c# 的图像编码/解码方式

asp.net-mvc - 带有 IIS 7 的 asp.net mvc url 上的尾部斜杠

asp.net - 在设计网页时遇到布局问题(1600 X 900 像素)

c# - RadioButtonFor 删除默认选中的

c# - 将6位数字解析为6个int数组