简体   繁体   中英

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

<html>
...
<body>
...
<partial name="_Nav" />

Inside my _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. Does this mean I need to do away with my _Nav partial and and lump all the code into one file? 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!

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.

Thanks for your help!

You don't have to store html in your ViewDataDictionary .

On every view that has extra links to add, store a List<string> , strings being urls, something like this:

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.

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 class="links">
        <partial name="_Nav" />
        @RenderSection("Html", required: false)
    </div>
....

_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>
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM