在 <a> Razor 中使用 if 语句拆分标签



我有几个<div>组成一个菜单,用户可以在其中选择几个选项之一。但是,有时该选项需要将用户带到另一个页面,即有时它需要有一个链接环绕它。

以下是到目前为止我的方法的简化版本:

@if (true)
{
    <a href="@Url.Action("Details", "Item", new { id = 1 })">
}
<div>
    A div with some stuff in it...
</div>
@if (true)
{
    </a>
}

这会导致以下错误:

Parser Error Message:
The if block is missing a closing "}" character.  Make sure you have a matching "}" character for all the "{" characters within this block, and that none of the "}" characters are being interpreted as markup.

我找到了这篇文章,但它对我没有帮助,因为给出的答案使用Html.Raw()<text>,这将阻止我使用链接中的@Url.Action()

有没有办法做到这一点,或者我需要做一些完全不同的事情?

你可以像这样做你所拥有的:

@if (true)
{
    @Html.Raw("<a href='" + Url.Action("Details", "Item", new { id = 1 }) + "'>")
}
<div>
    A div with some stuff in it...
</div>
@if (true)
{
    @Html.Raw("</a>")
}

虽然,第二个选项可能更干净一些,您可以在其中将div 和内容设置为部分视图:

@if (true)
{
    <a href="@Url.Action("Details", "Item", new { id = 1 })">
        @Html.Partial("PartialName")
    </a>
}else {
    @Html.Partial("PartialName")
}

第三种选择是编写自己的 Html 助手。

正如线程中所述 Razor 视图将不允许拆分,这可以实现,而无需@Html.Raw()意味着您的 HTML 不必以字符串结尾:

@if (1 == 1) { 
    @:<div> 
}
<div>some content</div>
@if (1 == 1) { 
    @:</div>
}

在 Dotnet 6 中,您还可以执行以下操作,使用 HTML 帮助程序时,最佳做法是使用 PartialAsync。

@if (true)
{
    <div class="v-application">
        <a href="@Url.Action("Details", "Item", new { id = 1 })">
            @await Html.PartialAsync("~/Pages/Partial/_LoginForm.cshtml")
        </a>
    </div>
}
else
{
    @await Html.PartialAsync("~/Pages/Partial/_LoginForm.cshtml")
}

参考: https://learn.microsoft.com/en-us/aspnet/core/mvc/views/partial?view=aspnetcore-6.0

最新更新