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

后端 未结 6 1449
执念已碎
执念已碎 2020-11-29 15:24

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 h

相关标签:
6条回答
  • 2020-11-29 15:57

    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.

    0 讨论(0)
  • 2020-11-29 16:02

    I prefer to use the razor html helper from Client Dependency dll

    Html.RequireCss("yourfile", 9999); // 9999 is loading priority 
    
    0 讨论(0)
  • 2020-11-29 16:09

    layout works the same as an master page. any css reference that layout has, any child pages will have.

    Scott Gu has an excellent explanation here

    0 讨论(0)
  • 2020-11-29 16:17

    I tried adding a block like so:

    @section styles{
        <link rel="Stylesheet" href="@Href("~/Content/MyStyles.css")" />
    }
    

    And a corresponding block in the _Layout.cshtml file:

    <head>
    <title>@ViewBag.Title</title>
    @RenderSection("styles", false);
    </head>
    

    Which works! But I can't help but think there's a better way. UPDATE: Added "false" in the @RenderSection statement so your view won't 'splode when you neglect to add a @section called head.

    0 讨论(0)
  • 2020-11-29 16:18

    Using

    @Scripts.Render("~/scripts/myScript.js")
    

    or

    @Styles.Render("~/styles/myStylesheet.css")
    

    could work for you.

    https://stackoverflow.com/a/36157950/2924015

    0 讨论(0)
  • 2020-11-29 16:19

    You can this structure in Layout.cshtml file

    <link href="~/YourCssFolder/YourCssStyle.css" rel="stylesheet" type="text/css" />
    
    0 讨论(0)
提交回复
热议问题