Home > Enterprise >  How can I render section in a children Partial view?
How can I render section in a children Partial view?

Time:02-01

The runtime&SDK I am using is the newest version .net 6

Here are three Partial views in _Layout.cshtml of my project: header.cshtml/aside.cshtml/footer.cshtml .

Why I speared them to three parts for there are so many codes for them that I have to speare for coding convenient.

Now I need to add a section to the header.cshtml. Here is my code:

<header>
    ///some other codes
    @RenderSection("ProductNav", required: false)
</header>

No matter there is a section "ProductNav", after the program ran, the page will all be blank without any error.

I found that it seems I can not use the RenderSection in a children Partial view.

It seems there is another way by using the Html.Partial to achieve this.

However, it needs to convert the views that I want to add to string. That's so troublesome.

Is there an easy way can achieve this? Thank you.

CodePudding user response:

You want to show navbar on partial pages, You use partial view to achieve this function, But user can't add css style in partial view directly.

My idea is you can create a External CSS file in wwwroot and use it in page whitch needs to load partial view.

I write a demo to demonstrate the feasibility of this idea.

Views/Shared/_header.cshtml

<h2>This is head Partial View H2</h2>
<p>This is head Partial View P</p>

wwwroot/css/header.css

h2 {
    color: blue;
}

p {
    color: red;
}

views/Shared/_Layout.cshtml

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>@ViewData["Title"] - EmptyNEt5MVc</title>
    <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
    <link rel="stylesheet" href="~/css/site.css" />
   //add the css file in here
    @await RenderSectionAsync("Css", required: false)
</head>
//.........

View

@{
    ViewData["Title"] = "Privacy Policy";
}
//use partial view 
<partial name="_header" />

<h1>@ViewData["Title"]</h1>

<p1>Use this page to detail your site's privacy policy.</p1>

//reference css file
@section Css{
    <link rel="stylesheet" href="~/css/header.css" />
}

Then you can see the `header partial view' load the css file successfully

enter image description here

=============================================

In fact, View Component is more suitable for navigation bar than Partial View, There is a document about View Component.

  •  Tags:  
  • Related