Search code examples
asp.net-mvcmodel-view-controller

How to use the @RenderBody()?


I am new to ASP.NET MVC. I got a template on the internet and implemented it successfully in my mvc root project. However when I put @Renderbody () ... in the zone where I put it, it does a "rendering" of the official microsoft template and the original one from when we created an MVC project. Can someone tell me why this happens?

Layout RenderBody()

what happens


Solution

  • In Razor, there are two kinds of views: regular .cshtml files and and layouts, that (not same as with ASPX pages, there master pages have the suffix .master), also have the suffix .cshtml, but usually they aren't rendered directly from the controller, however you must specify the layout of the page:

    @{
      Layout = "_Layout";
    }
    

    Then Razor will look for _Layout.cshtml in the current directory and the directory /Views/Shared, like any view. If you set Layout = null;, then the page won't have a layout.

    This code can also be at /Views/_ViewStart.cshtml, because by the convention, any code in this file will be run before the code in the view (so you can override the layout specified in this file from the view).

    When Razor Engine should render a view with a layout, it renders only the layout. But, if when you call the method RenderBody(), it renders the view and puts it in the RenderBody() call's place.

    There is a similar method, RenderSection(), which renders a single section of the view. Give a look on the <head> element of your _Layout.cshtml:

    <html>
      <head>
        <!-- ... -->
        @RenderSection("scripts", required: false)
        <!-- ... -->
      </head>
      <!-- ... -->
    </html>
    

    The call to RenderSection() renders the section scripts. the parameter required: false specify that the casn be a view without the section scripts; Without it, such view will trigger a runtime error.

    Now, please look the follow view:

    <div>Some View</div>
    

    The call to RenderBody() will be replaced by <div>Some View</div>.

    However, if the view looks like as follows:

    <div>Some View</div>
    
    @section scripts {
      <script src="jsfile.js"></script>
    }
    

    Then, RenderBody() will be the same, but the call RenderSection("scripts", ...) will be replaced by <script src="jsfile.js"></script>. Sections enable you to create a main content, but also secondary contents - such as a header, special scripts/styles, etc.

    Some comment: layouts can have layouts too - it enable you to create a nested page, for example in a company - the main layout, a special layout for the marketing class, a layout for the management sections...