Bella O.
Bella O.

Reputation: 43

Mvc section not rendered in head but in body

I encountered a strange behavior for @RenderSection in the head section of _Layout.

@section AddToHead{ 
    <meta name="test" />
    <open-graph og-title="@Model.Test.OG.Title" og-image="@Model.Test.OG.Image" og-url="@Model.Test.OG.Url" og-type="@Model.Test.OG.Type"></open-graph>
}
  1. meta => is plain html
  2. open-graph => is a taghelper which returns html

and added on _Layout

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    @await RenderSectionAsync("AddToHead", required: false)
</head>

I tried already with RenderSectionAsync and RenderSection. No difference.

When I check the result on page it is as follows (total different result)

View Source Code

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <meta name="test" />
    <div><meta property='og:title' content='TestTitle' /><meta property='og:type' content='Article' /><meta property='og:url' content='TestURL' /><meta property='og:image' content='TestBild' /></div>
</head>

Developer Tools

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <meta name="test" />

</head>
<body>
  <div><meta property='og:title' content='TestTitle' /><meta property='og:type' content='Article' /><meta property='og:url' content='TestURL' /><meta property='og:image' content='TestBild' /></div>
</body>

Facebook sees my site like Developer Tools does.

What I'm doing wrong? Is this even possible?

Upvotes: 2

Views: 982

Answers (2)

ChainsManipulator
ChainsManipulator

Reputation: 31

I had a similar problem, that included not only @RenderSection, but also <meta> tags and all other <head> content.

The solution was to move all usings from layout to a separate file _ViewImports.cshtml as stated in documentation.

Upvotes: 1

N. Taylor Mullen
N. Taylor Mullen

Reputation: 18301

Developer tools shows how the browser interprets your HTML which is why you're seeing a difference between viewing source and the developer tools.

As for why that's happening, <div> tags in the <head> are problematic. Most browsers these days will interpret those <div> tags as if they were in the body. If you were to render your <meta /> tags without the surrounding div all should be fine.

Upvotes: 1

Related Questions