Reputation: 65
I am trying to add a css file to a basic html file (in /dashboard along with the css file) and it is not working:
@{
ViewBag.Title = "Index";
}
<head>
<link rel="stylesheet" href="~/Views/Dashboard/Dashboard.css" type="text/css" />
</head>
<body>
<h2 id="yes">Index</h2>
<h1>@ViewBag.test</h1>
</body>
I have tried multiple ways, including adding the file to the contents folder, and adding
@Styles.Render("~/Content/css")
Is this a syntax issue? Or a lack of understanding of how the layout system works? Still wrapping my head around asp.net and MVC...
Upvotes: 3
Views: 13318
Reputation: 719
You are not supposed to be loading CSS under the @section Scripts
. There's a reason CSS is loaded first!
For example, check this reference here by Patrick Sexton: Call CSS First
Ensuring the calls for CSS files come first helps ensure the browser gets it first. This saves time by reducing network calls and not letting javascript activity delay the browser from getting CSS
If you want to load different CSS files depending on the .cshtml
file, and assuming they all use the same _Layout.cshtml
, you can do something like this:
On your _Layout.cshtml
, in between your <head>
HTML tag, write this:
@RenderSection("Stylesheets", required: true)
Putting this in your <head>
tag will ensure it gets loaded first!
Note: The required: true
part is optional.
Then, on your .cshtml
Views, add this at the top:
@section Stylesheets {
}
And inside there, load your <link>
tags.
Upvotes: 5
Reputation: 28
Try this below at end of the body tag
@section Scripts
{
<link href="~/Content/yourcssname.css" rel="stylesheet" />
}
Upvotes: -2