How to Reference a .CSS File on a Razor View

How to reference a .css file on a razor view?

For CSS that are reused among the entire site I define them in the <head> section of the _Layout:

<head>
<link href="@Url.Content("~/Styles/main.css")" rel="stylesheet" type="text/css" />
@RenderSection("Styles", false)
</head>

and if I need some view specific styles I define the Styles section in each view:

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

Edit: It's useful to know that the second parameter in @RenderSection, false, means that the section is not required on a view that uses this master page, and the view engine will blissfully ignore the fact that there is no "Styles" section defined in your view. If true, the view won't render and an error will be thrown unless the "Styles" section has been defined.

How to include CSS styles inline in Razor view?

I guess you will need to have a custom helper for that. On top of my head, there is no such a method to render the css path including the absolute path of the website.

e.g. http:www.example.com/css/EmailStyles.css

Add css file to cshtml file?

Try this below at end of the body tag

@section Scripts
{
<link href="~/Content/yourcssname.css" rel="stylesheet" />
}

ASP.Net MVC: How to use razor variable in CSS file

By default, MVC does not support writing server side codes in external CSS file and external Javascript files.

For your case to work, you can add an internal stylesheet in your view file itself, it will work.

Eg:

@{
ViewBag.Title = "Title";
}
<style>
.test {
background: url('@Model.LogoUrl') no-repeat scroll 0 0 transparent;
}
</style>

How to use @RenderPage to include CSS content inline - MVC Razor

So, it turns out that @RenderPage is not what I was looking for...

what I needed is this:

@Html.Raw(File.ReadAllText(Server.MapPath("~/CSS/_ExportStyles.min.css")))



Related Topics



Leave a reply



Submit