3

In my ASP.NET MVC application, in my _ViewStart.cshtml file, I have code like the following -

<div>SHOW THIS</div>

@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}

When the page is rendered, I expect "SHOW THIS" to be displayed above the content in the _Layout.cshtml page, but instead "SHOW THIS" is appearing below the the content in the _Layout.cshtml page.

Is this correct? If not, any idea why this would happen? Can you suggest how to make it show above the _Layout.cshtml content? Thanks!

2 Answers 2

3

The layout is going to get loaded first and the content will be inserted into the layout's render content section. If you want something to appear in the layout for this view you could try setting a ViewBag object in the controller and then check for that ViewBag object in the Layout.

Or you could use an optional section in the layout and then define it in the view:

In layout:

@RenderSection("aboveSection", required: false)

Then in your view:

@section aboveSection{
    <div>SOME CONTENT</div>
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the answer Matt! That is strange that it would work like that.
0

That is the expected behavior. The "_Layout.chshtml" line only specifies which parent template it would you use.

To re-arrange content, make the adjustments in _Layout.cshtml and take note of where @RenderBody() is located.

Comments

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.