我正在尝试向 Razor 页面添加几个 if 语句。我正在更改的页面在更改之前工作但是当我添加我在下面的代码示例中突出显示的 block 时我收到此错误:
加载 Razor 脚本时出错 ~/macroscripts/genericpage.cshtml 代码块缺少结束符“}”。确保此 block 中的所有“{”字符都具有匹配的“}”字符,并且没有任何“}”字符被解释为标记。
if (publishedRightHandPods.Any())
{
foreach(var rh in publishedRightHandPods)
{
if (rh.image.GetType() == typeof(DynamicXml))
{
if (rh.link.GetType() == typeof(DynamicXml))
{
var linkSupplied = !String.IsNullOrEmpty(rh.link.url) && !String.IsNullOrWhiteSpace(rh.link.url);
var titleSupplied = !String.IsNullOrEmpty(rh.title) && !String.IsNullOrWhiteSpace(rh.title);
@* *************** *@
@* I'M ADDING THIS *@
@* *************** *@
@{
if (linkSupplied) {
<a href="@(rh.link.url)">
}
}
@* ****************** *@
@* END OF ADDED BLOCK *@
@* ****************** *@
<div class="side-pod" style="background: url('@(rh.image.mediaItem.Image.umbracoFile)') no-repeat scroll 0 0 transparent; height: @(rh.image.mediaItem.Image.umbracoHeight)px">
@{
if (titleSupplied)
{
<h2 class="title" style="color: #@(rh.textColour);">@Html.Raw(rh.title.ToString())</h2>
}
}
@{
if (!String.IsNullOrEmpty(rh.linkText) && !String.IsNullOrWhiteSpace(rh.linkText) && !String.IsNullOrEmpty(rh.link.url) && !String.IsNullOrWhiteSpace(rh.link.url))
{
<a class="findoutmore-btn" href="@(rh.link.url)">@(rh.linkText)</a>
}
}
</div>
@* *************** *@
@* I'M ADDING THIS *@
@* *************** *@
@{
if (linkSupplied) {
</a>">
}
}
@* ****************** *@
@* END OF ADDED BLOCK *@
@* ****************** *@
}
}
}
我不明白为什么 <div>
中的 if 语句正在工作但是当我在 div 之外添加新的(类似的)语句时我得到了错误。
****更新****
如果我删除围绕我添加的 if 语句的 @{},如下所示:
if (linkSupplied) {
<a href="@(rh.link.url)">
}
我在屏幕上看到了这个:
最佳答案
当你需要在 if
中打开一个 HTML 标签时声明但你不想关闭它,我建议你使用@Html.Raw()
:
@if (linkSupplied) {
@Html.Raw(string.Format("<a href=\"{0}\">", rh.link.url))
}
...然后,当你关闭A
标记...
@if (linkSupplied) {
@Html.Raw("</a>")
}
关于c# - .cshtml 文件中的 Razor - 添加额外的 'if' 语句会出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18908852/