C# 简单的 If/Else Razor 语法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9710431/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 08:30:44  来源:igfitidea点击:

Simple If/Else Razor Syntax

c#asp.net-mvcrazorhtml-table

提问by Shane LeBlanc

I'm trying to do a simple If/Else within a foreach with this code:

我正在尝试使用以下代码在 foreach 中执行一个简单的 If/Else:

@{
var count = 0;
foreach (var item in Model)
{
    if (count++ % 2 == 0)
    {
        @:<tr class="alt-row">
    } else { 
        @:<tr>
    }
        <td>
            @Html.DisplayFor(modelItem => item.Title)
        </td>
        <td>
            @Html.Truncate(item.Details, 75)
        </td>
        <td>
            <img src="@Url.Content("~/Content/Images/Projects/")@item.Images.Where(i => i.IsMain == true).Select(i => i.Name).Single()" 
                alt="@item.Images.Where(i => i.IsMain == true).Select(i => i.AltText).Single()" class="thumb" />
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.ProjectId }) |
            @Html.ActionLink("Details", "Details", new { id = item.ProjectId }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.ProjectId })
        </td>
    </tr>
}
}

I get a parse error "Encountered end tag "tr" with no matching start tag. Are your start/end tags properly balanced?". Seems like the if statement doesn't wanna' work.

我收到解析错误“遇到没有匹配开始标签的结束标签“tr”。您的开始/结束标签是否正确平衡?”。似乎 if 语句不想工作。

采纳答案by Henk Holterman

Just use this for the closing tag:

只需将其用于结束标记:

  @:</tr>

And leave your if/else as is.

并保持你的 if/else 不变。

Seems like the if statement doesn't wanna' work.

似乎 if 语句不想工作。

It works fine. You're working in 2 language-spaces here, it seems only proper not to split open/close sandwiches over the border.

它工作正常。你在这里工作在 2 个语言空间,似乎只有在边界上不分开打开/关闭三明治才是正确的。

回答by Jeff

I would just go with

我只想和

<tr @(if (count++ % 2 == 0){<text>class="alt-row"</text>})>

Or even better

或者更好

<tr class="alt-row@(count++ % 2)">

this will give you lines like

这会给你像

<tr class="alt-row0">
<tr class="alt-row1">
<tr class="alt-row0">
<tr class="alt-row1">

回答by Michiel

A little bit off topic maybe, but for modern browsers (IE9 and newer) you can use the css odd/even selectors to achieve want you want.

可能有点离题,但对于现代浏览器(IE9 和更新版本),您可以使用 css 奇数/偶数选择器来实现您想要的。

tr:nth-child(even) { /* your alt-row stuff */}
tr:nth-child(odd) { /* the other rows */ }

or

或者

tr { /* all table rows */ }
tr:nth-child(even) { /* your alt-row stuff */}

回答by Steven Wexler

To get rid of the if/else awkwardness you could use a using block:

为了摆脱 if/else 的尴尬,你可以使用 using 块:

@{
    var count = 0;
    foreach (var item in Model)
    {
        using(Html.TableRow(new { @class = (count++ % 2 == 0) ? "alt-row" : "" }))
        {
            <td>
                @Html.DisplayFor(modelItem => item.Title)
            </td>
            <td>
                @Html.Truncate(item.Details, 75)
            </td>
            <td>
                <img src="@Url.Content("~/Content/Images/Projects/")@item.Images.Where(i => i.IsMain == true).Select(i => i.Name).Single()" 
                    alt="@item.Images.Where(i => i.IsMain == true).Select(i => i.AltText).Single()" class="thumb" />
            </td>
            <td>
                @Html.ActionLink("Edit", "Edit", new { id=item.ProjectId }) |
                @Html.ActionLink("Details", "Details", new { id = item.ProjectId }) |
                @Html.ActionLink("Delete", "Delete", new { id=item.ProjectId })
            </td>
        }
    }
}

Reusable element that make it easier to add attributes:

可以更轻松地添加属性的可重用元素:

//Block is take from http://www.codeducky.org/razor-trick-using-block/
public class TableRow : Block
{
    private object _htmlAttributes;
    private TagBuilder _tr;

    public TableRow(HtmlHelper htmlHelper, object htmlAttributes) : base(htmlHelper)
    {
        _htmlAttributes = htmlAttributes;
    }

    public override void BeginBlock()
    {
        _tr = new TagBuilder("tr");
        _tr.MergeAttributes(HtmlHelper.AnonymousObjectToHtmlAttributes(_htmlAttributes));
        this.HtmlHelper.ViewContext.Writer.Write(_tr.ToString(TagRenderMode.StartTag));
    }

    protected override void EndBlock()
    {
        this.HtmlHelper.ViewContext.Writer.Write(_tr.ToString(TagRenderMode.EndTag));
    }
}

Helper method to make razor syntax clearer:

使 razor 语法更清晰的辅助方法:

public static TableRow TableRow(this HtmlHelper self, object htmlAttributes)
{
    var tableRow = new TableRow(self, htmlAttributes);
    tableRow.BeginBlock();
    return tableRow;
}