Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

asp.net mvc - How to reference a .css file on a razor view?

I know how to set .css files on the _Layout.cshtml file, but what about applying a stylesheet on a per-view basis?

My thinking here is that, in _Layout.cshtml, you have <head> tags to work with, but not so in one of your non-layout views. Where do the <link> tags go?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...