liamcook
liamcook

Reputation: 143

.NET - Adding an extra style sheet to a razor view ontop of layout

I'm creating a new view and I want to add some custom CSS, so I created a new CSS sheet in the content folder called ClientDetails and referenced it at the top of the sheet as I read on another thread of adding specific CSS sheets to a view:

@model Linkofy.Models.Client

@{
ViewBag.Title = "Details";
}

@section Styles {
<link href="@Url.Content("~/Content/ClientDetails.css")" rel="stylesheet" type="text/css" />
}

<h2>@Html.DisplayFor(model => model.clientN)</h2>

However with the @section Styles bit I get this error:

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

Though if I remove the @section styles bit it works fine, I wondered if its only rendering that sheet and not the layout CSS if it's overriding it or something? how do I add it on top of all the other sheets needed for the display.

I have tried looking around for the answer to this though if it is a duplicate please link me to the question and I will close it, thanks!

Upvotes: 1

Views: 2630

Answers (2)

Skyler Sanders
Skyler Sanders

Reputation: 175

Problem:

Server Error in '/' Application. The following sections have been defined but have not been rendered for the layout page "~/Views/Shared/_Layout.cshtml": "Styles". Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.Web.HttpException: The following sections have been defined but have not been rendered for the layout page "~/Views/Shared/_Layout.cshtml": "Styles".

Solution:

In your ~/Views/Shared/_Layout.cshtml render the section using

    @RenderSection("Styles", required: false)

See https://msdn.microsoft.com/en-us/library/gg537886(v=vs.111).aspx for more details.

Also you must declare the layout:

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

Upvotes: 2

Matt Spinks
Matt Spinks

Reputation: 6698

The reason you are getting this error is explained in the message. You probably have something like this in your layout page:

@RenderSection("Styles")

When you use it like that, it's required by default. Every page will be required to have the additional style section. Otherwise, you get the error you are seeing now. What you need to do is make that section not required:

@RenderSection("Styles", required: false)

Upvotes: 0

Related Questions