[英]Razor Pages: How to include pagesection in a partial page?
I have a Razor Pages layout page that includes a nav bar as a partial page我有一个 Razor Pages 布局页面,其中包含一个导航栏作为部分页面
<html>
...
<body>
...
<partial name="_Nav" />
Inside my _Nav.cshtml在我的 _Nav.cshtml 里面
<div class="links">
<a href="#link1">link 1</a>
<a href="#link2">link 2</a>
<!-- custom links that are set by each page go here-->
</div>
This layout is used by every page in the website.网站中的每个页面都使用此布局。 I would like to be able include "extra" links that pertain to each page in the website.
我希望能够包含与网站中每个页面相关的“额外”链接。
I've tried doing it was @RenderSection
, but it seems that sections are only allowed in the Layout
page.我试过这样做是
@RenderSection
,但似乎只允许在Layout
页面中使用部分。 Does this mean I need to do away with my _Nav
partial and and lump all the code into one file?这是否意味着我需要取消我的
_Nav
部分并将所有代码集中到一个文件中? Or is there a way to keep an organized code structure and still pass some code around?或者有没有办法保持有组织的代码结构并仍然传递一些代码? With jinja2 code blocks this is no problem, so I'm hoping there is a nice way in Razor Pages as well!
使用 jinja2 代码块这没问题,所以我希望 Razor Pages 也有一个不错的方法!
Also, I really don't want to pass full html strings from the c# class out to the html, I'm already passing out any variables I need in the links.另外,我真的不想将完整的 html 字符串从 c# 类传递给 html,我已经在链接中传递了我需要的任何变量。
Thanks for your help!谢谢你的帮助!
You don't have to store html in your ViewDataDictionary
.您不必将 html 存储在
ViewDataDictionary
。
On every view that has extra links to add, store a List<string>
, strings being urls, something like this:在每个需要添加额外链接的视图上,存储一个
List<string>
,字符串是 url,如下所示:
View:看法:
@{
ViewData["Links"] = new List<string>(){ "https://www.google.com", "https://www.facebook.com" };
}
Then in your Layout view:然后在您的布局视图中:
<partial name="_Nav" view-data="@ViewData" />
Now in your partial view:现在在您的部分视图中:
//Default Links
@if (ViewData["Links"] != null)
{
//We have extra links
List<string> links = (List<string>)ViewData["Links"];
foreach (string link in links)
{
<a href="@link">link1</a>
}
}
RenderSection
can only be called from a layout page. RenderSection
只能从布局页面调用。
There is no such plugin to add the dynamic link to the partial view.没有这样的插件可以将动态链接添加到局部视图。
As a workaround,you could put a div outside the _Nav.cshtml like below and use RenderSection
to dynamic add link to the div:作为一种解决方法,您可以将一个 div 放在 _Nav.cshtml 之外,如下所示,并使用
RenderSection
动态添加到 div 的链接:
....
<div class="links">
<partial name="_Nav" />
@RenderSection("Html", required: false)
</div>
....
_Nav.cshtml: _Nav.cshtml:
<a href="#link1">link 1</a>
<a href="#link2">link 2</a>
Test View:测试视图:
@page
@model IndexModel
//do your stuff...
@section Html
{
<a href='#link3'>link3</a>
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.