简体   繁体   English

使用 _Layout.cshtml 在 Razor Pages 中查看特定的 css

[英]View specific css in Razor Pages with _Layout.cshtml

I have a _Layout.cshtml file with a <head> section that looks like so:我有一个带有<head>部分的_Layout.cshtml文件,如下所示:

<head>
    <title>Dashboard</title>
    <link rel="stylesheet" href="css/bootstrap.min.css"/>
    <link rel="stylesheet" href="css/layout.css"/>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>

I have a View called Index.cshtml (that is using _Layout.cshtml as a layout) with a <head> section that looks like so:我有一个名为Index.cshtml的视图(即使用_Layout.cshtml作为布局),其<head>部分如下所示:

<head>
    <link rel="stylesheet" href="css/Home/Index.css"/>
    <script src="https://cdn.datatables.net/v/bs/jq-3.2.1/dt-1.10.16/datatables.min.js"></script>
    <link href="https://cdn.datatables.net/1.10.16/css/dataTables.bootstrap.min.css" rel="stylesheet" />
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
</head>

Now this line in Index.cshtml is styling my DataTables correctly, but it is messing up my layout page even though it is located in the Index.cshtml and not the _Layout.cshtml :现在Index.cshtml这一行正确地设置了我的 DataTables 样式,但是即使它位于Index.cshtml而不是_Layout.cshtml ,它也会弄乱我的布局页面:

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

I must be getting a bit messed up with how my css is working throughout my web app.我一定对我的 css 在整个网络应用程序中的工作方式有点困惑。 I have tried using @section but I couldn't get that to work either.我试过使用@section但我也无法使用它。

So my question is how can I make the css in Index.cshtml only apply to that page rather than also affecting the css in _Layout.cshtml ?所以我的问题是如何使Index.cshtml的 css 仅适用于该页面而不影响_Layout.cshtml的 css?

In your _Layout.cshtml use the RenderSection method with the required argument set to false:在您的_Layout.cshtml使用RenderSection方法并将所需参数设置为 false:

<head>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" /> 
    ....
    @RenderSection("head",false)
</head>

Then in your view that requires additional css:然后在您看来,需要额外的 css:

@section head {      
  <link href="my_view_specific_css.css" rel="stylesheet" />    
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM