在 ASP.NET MVC 的 _ViewStart 中定义@helper?

发布于 2024-12-17 12:04:34 字数 63 浏览 4 评论 0 原文

是否可以在 _ViewStart.cshtml 中定义共享 @helper,以便它可在其目录中的所有视图中使用?

Is it possible to define a shared @helper in _ViewStart.cshtml so that it will be available for use in all views in its directory?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

情话墙 2024-12-24 12:04:34

不,在 _ViewStart 中定义 @helper 不起作用,但您可以为共享助手创建一个新的 Razor 视图并将其放置在 App_Code 文件夹中。一个小缺点是必须在与视图同名的类型上以静态方法的形式调用帮助器,这使得该技术变得更加冗长。

这是一个示例:

视图中的帮助程序方法位于此处:~/App_Code/RazorHelpers.cshtml:

@helper LiLink(string url, string title)
{
    <li><a href="@url">@title</a></li>
}

视图中的帮助程序用法:

@RazorHelpers.LiLink("/about","About")

请参阅此SO问题:应用程序代码中的 Razor 助手文件夹

No, defining the @helper in _ViewStart will not work, but you can create a new Razor view for shared helpers and place it in the App_Code folder. One minor drawback is the helper must be called as a static method on a type with the same name as the view making this technique a little more verbose.

Here is an example:

Helper Method in View located here: ~/App_Code/RazorHelpers.cshtml:

@helper LiLink(string url, string title)
{
    <li><a href="@url">@title</a></li>
}

Helper Usage in a View:

@RazorHelpers.LiLink("/about","About")

See this SO Question: Razor Helper In App Code Folder

‘画卷フ 2024-12-24 12:04:34

您可以将助手添加到单独的文件中,并且它将可供您的所有视图使用。请参阅 Scoot Gu 的帖子:http://weblogs.asp.net/scottgu/archive/2011/05/12/asp-net-mvc-3-and-the-helper-syntax-within-razor.aspx

You can add the helper in a separate file and it will be available to all your views. See the Scoot Gu's post about it: http://weblogs.asp.net/scottgu/archive/2011/05/12/asp-net-mvc-3-and-the-helper-syntax-within-razor.aspx

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文