2

I'm trying to output some additional <head> metadata in views which are rendered using Html.RenderPartial() via a shared Partial View.

My _Layout.cshtml looks like this:

<head>
    //...
    @if (IsSectionDefined("AdditionalMeta")) { 
        RenderSection("AdditionalMeta"); 
    }
    //...
</head>

...My shared view (_Title.cshtml) looks like this:

@model TitleViewModel

@section AdditionalMeta {
    @if (Model != null && Model.Title != null)
    {     
        //additional <meta> tags using Model properties here  
    }
}

//...other irrelevant code

...And Index.cshtml view implementing _Title.cshtml:

@model TitleViewModel

@{
    Html.RenderPartial("_Title", Model);
}

This outputs nothing though as IsSectionDefined("AdditionalMeta") in _Layout.cshtml returns false - I've tried moving the "AdditionalMeta" @section to Index.cshtml instead - this makes IsSectionDefined("AdditionalMeta") in _Layout.cshtml return true but gives the following error:

The following sections have been defined but have not been rendered for the layout page "~/Views/Shared/_Layout.cshtml": "AdditionalMeta".

Am I missing something or approaching this the wrong way? Thanks!

EDIT: Faby's solution is correct, provided that the "AdditionalMeta" @section is declared in Index.cshtml rather than _Title.cshtml

1 Answer 1

1

did you try with just

RenderSection("AdditionalMeta", false); 

instead of

@if (IsSectionDefined("AdditionalMeta")) { 
    RenderSection("AdditionalMeta"); 
}

refer here for documentation

Sign up to request clarification or add additional context in comments.

2 Comments

yes, I initially had @RenderSection("AdditionalMeta", required: false)
your solution is correct provided that the "AdditionalMeta" @section is declared in Index.cshtml rather than _Title.cshtml

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.