asp.net mvc - different views need different meta tag in <head> inside layout page

asp.net-mvc, html, razor

Solution

It seems to me the easiest way would be to define a section in the `<head>` tag of your layout file that you can choose to populate with data in your views

<head>
    <meta charset="utf-8" />
    <title>@ViewBag.Title - My ASP.NET MVC Application</title>
    <link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
    <meta name="viewport" content="width=device-width" />
    <!-- Adding a RenderSection here, mark it as not required-->
    @RenderSection("AdditionalMeta", false)
    @Styles.Render("~/Content/css")
</head>

Now, in any view in which you need to add additional meta data, simply add the following code at the end/beginning (after model declarations) of your view file

@section AdditionalMeta
{
    <meta name="robots" content="noindex,nofollow"/>
}

Since all of the Razor stuff is processed server side, there would be no issues in a) having JS append items given that some crawlers do not implement JS and b)no late appending to `<head>` tag/etc. Also, being marked as not required means that you only have to update the pages that you want to not be indexed and not have to set a variable on every single page in your application.

Problem

I would like to stop a few of my pages from showing up in search results. My understanding is that I add the following to the `<head>` section of the page: ``` <meta name="robots" content="noindex,nofollow"/> ``` The problem is that my pages use a common Layout page. Something like: ``` @{ Layout = "~/Views/Shared/_VanillaLayout.cshtml"; } ``` Inside the layout page is the head section with a whole lot of links, scripts and meta tags. I don't want to duplicate this for indexable and non-indexable pages. From my research I have found that: - - Having multiple `<head>` sections is bad. - Having the robot meta tag outside of head is bad. - Using robots.txt is more than I want and is bad. - Trying to pass a model into the layout is a bit of an overkill (need all models to inherit from some base and many pages are purely presentation and don't even have a model) and is bad. Hopefully, I am missing something and there is a good (non-bad) way to do this or one of the approaches I have mentioned above is not so bad after all.

Original source

Related problems