剃刀代码块在ASP.NET Core 3.1中不起作用

时间:2020-01-22 10:17:21

标签: c# razor asp.net-core-3.1

@Helpers离开了Razor in ASP.NET Core 3.1,现在建议使用Razor代码块。 https://docs.microsoft.com/en-us/aspnet/core/mvc/views/razor?view=aspnetcore-3.1#razor-code-blocks

不幸的是,如果我添加示例代码

@{
    void RenderName(string name)
    {
    <p>Name: <strong>@name</strong></p>
    }
}

到Razor页面(cshtml),我收到错误信息,因为Intelisence无法解析值,它表明该位置不接受HTML,并且预期会有c#代码。如何使用Razor代码块?

enter image description here

6 个答案:

答案 0 :(得分:0)

您尝试过Html.Raw($"<p>Name: <strong>{@name}</strong></p>")吗?

Documentation

答案 1 :(得分:0)

我看到HTML代码应作为Razor(C#)代码使用。那是问题。

尝试使用:

<text>
<p>Name: <strong>@name</strong></p>
</text>

或者:

@:<p>Name: <strong>@name</strong></p>

在有块时很有用,但是如果仅使用一行,则可以使用“ @:”

答案 2 :(得分:0)

在我的情况下,问题是 Resharper 。更新并不能解决问题(版本2020.2.4)。现在通过“扩展”->“管理扩展”禁用它。 花了我很长时间才找到原因。

更新

通过重新激活了Resharper并禁用了.cshtml文件的代码检查。 “扩展名”->“恢复程序”->“选项”->“代码检查”->“忽略的代码”->“文件掩码”->“添加”->“ *。cshtml”。

答案 3 :(得分:0)

如果我做对了,那么也许这就是您所需要的

android:name

答案 4 :(得分:0)

我相信这个问题已经解决,事件智能感知功能已在VS 2019(v 16.7.5)上正常运行。

Index.cshtml

@{
    ViewData["Title"] = "Home Page";
}

<div class="text-center">
    <h1 class="display-4">Welcome</h1>
    <p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
    @RenderDivision()
</div>

@{ 
    Microsoft.AspNetCore.Html.IHtmlContent RenderDivision()
    {
        return Html.Raw("<div>This is my div tag!</div>");
    }
}

渲染:

enter image description here

答案 5 :(得分:0)

https://github.com/dotnet/AspNetCore.Docs/issues/18543#event-3384859964

关键词功能,使它起作用...多么奇怪

啊,有趣的是,您看到的是C#限制。 说@functions {...}你的意思是将以下内容添加到我的 @ {}必需的类主体将以下内容添加到类中的方法中 身体(局部功能)。因此,由于C#不支持重载 本地函数,您无法在@ {}中使用它们。

@functions 
{
     void RenderName(string name)
    {
        <p>Name: <strong>@name</strong></p>
    }
}
相关问题