【问题标题】:Render section on Razor PageRazor 页面上的渲染部分
【发布时间】:2019-06-20 10:26:33
【问题描述】:

使用 Razor 页面 @RenderSection 在 Razor 页面上似乎不可用,我得到“RenderSection 在当前上下文中不存在”

我有许多 Razor 页面,我试图在部分页面上使用部分页面,我想将一些随附的 css 和 Javascript 注入 css 和脚本部分

如果我只是在部分页面上定义部分,则不会呈现任何内容,因此经过一番搜索后,似乎在使用部分页面的页面上,您需要在各个部分中添加 RenderSection。

任何帮助将不胜感激。

【问题讨论】:

    标签: asp.net-core razor-pages


    【解决方案1】:

    您可能错过了在 ASP.NET Core 中使用 @RenderSection 的要点。 @RenderSection 应该只在Layout 页面如下:

     <script src="~/lib/jquery/dist/jquery.js"></script>
     @RenderSection("Scripts", required: false)
    

    那么Razor页面应该如下:

    @{
        ViewData["Title"] = "My Razor Page";
    
        Layout = "_Layout"; // If this specified in the `_ViewStart.cshtml` then you don't need it
    }
    
    <partial name="_YourPartial.cshtml"/>
    @section scripts {
        <script src="~/js/yourjs.js" asp-append-version="true"></script> // this is specific to this Razor page only and it will also be available on the partial view called inside this Razor Page
    }
    

    并且在生成 html 的过程中,Razor 页面上的scripts 将呈现如下:

    <script src="~/lib/jquery/dist/jquery.js"></script>
    <script src="~/js/yourjs.js" asp-append-version="true"></script>
    

    希望它能让你清楚!

    【讨论】:

    • 感谢您的回答,如何将内容从包含部分页面的部分页面注入部分
    • 您是否尝试在部分页面中引用某些库我是对的?
    • 我正在尝试获取部分页面以将 js 和 css 注入页面
    • @MikeU 请通过更新您的问题更清楚地说明。你想如何从部分页面注入 js 文件?这个部分页面是只包含那个js文件还是会通过控制器方法作为包含html代码和js的部分视图返回?
    猜你喜欢
    • 2015-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-14
    • 1970-01-01
    • 2019-08-26
    相关资源
    最近更新 更多