Create a fixed header and footer for all pages

Asked

Viewed 1,587 times

2

How to create a header with the logo and menu, and a footer with some information, and this header and footer are the same for all pages? No CTRL + C / CTRL + V, because if I change any items, I will have to change them page by page. This is possible?

  • 2

    What framework do you use?

  • 2

    Webforms or MVC, which MVC is it? Which ASP.Net? 5?

  • Good morning, yes it is possible. If you are using webform the form is as follows: masterpage for MVC use: Shared layout

  • There are many ways to do this, but perhaps the simplest is to use a template engine like the T4

1 answer

2


You create a page with layout basic that will be used on all pages. Usually it gets in this position in the project: ~/Views/Shared/_Layout.cshtml. Of course you can use other locations and names and can even have several layouts.

In general this page has everything that is around the main content and is fixed to all pages. Then both the header and the footer are placed in it. You can put everything in the header, including the beginning of HTML and the basic dependencies. It works as a include text.

But it is possible to have other forms like ~/Views/Shared/_Header.cshtml and ~/Views/Shared/_Footer.cshtml separately. It goes from your creativity and need.

It is important that this page has a @RenderBody() somewhere that is where the main content of the page will be inserted. In some cases you can use the RenderSection().

It is possible to make nests of these pages. That is, these pages may have another layouts inside of her.

Example:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>@ViewBag.Title</title>  
        <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css">
    </head>
    <body>
        <div id="header"> 
            Cabeçalho aqui           
        </div>
        <div id="main">
            @RenderBody()
        </div>
        <div id="footer"> 
            Rodapé aqui           
        </div>
    </body>
</html>

When you want to use this layout on some page you will have to add this code at the beginning of view specific:

@{
    ViewBag.Title = "Titulo da página específica";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<h1>Esta página</h1>
<p>Conteúdo</p> <!-- só um exemplo simples -->

I put in the Github for future reference.

You can create a _ViewStart.cshtml which is a view which will be used in all other views.

You can configure your use on controller also, but this will turn tutorial.

Obviously you can do much more sophisticated things, but the basic thing is this.

I hope you are not using classic ASP.Net yet. Then you would have to use Masterpages. The idea is the same, but obviously the way to use it is a little different.

Behold more direct from the source.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.