Defining a section for all views

2019-07-12 04:20发布

问题:

I've created a section for a footer in my asp.net MVC 3 Web Application:

<footer>
    @RenderSection("Footer", true)
</footer>

This footer will be the same on every page, so it doesn't make sense for me to define it for each and every view. So, is there any way I can globally declare this footer section for all views? The footer will contain code so as far as I know it's bad practice, if not impossible, to directly define it in the .cshtml file.

Thank you in advance.

回答1:

I have handled the same scenario by creating a partial view "_Footer" and place it on the "_Layout".

@ViewBag.Title

@Html.Partial("_Header")

<div id="content">
    <div id="nav-bar">
        @Html.Partial("_Menu")
   </div>

    <div class="container">
    @RenderBody()
</div>
</div>
<div id="footer">
    @Html.Partial("_Footer")
</div>

@Html.Partial("_Scripts")



回答2:

Sure:

<footer>
    @if (IsSectionDefined("footer"))
    {
        @RenderSection("footer")
    } 
    else
    {
        ... put your default footer here
    }
</footer>

And in views that you want to override the footer simply define the section.



回答3:

You can place the footer in your SiteLayout.cshtml. See this article for more information on using layouts with MVC 3.