How to add css/script only to a Partial view?

后端 未结 3 2092
挽巷
挽巷 2021-01-06 12:40

I need to load css and scripts only to a specific Partial view but at this moment this link and scripts are loaded in all views. The structure that I have is the main view e

相关标签:
3条回答
  • 2021-01-06 13:21

    You cannot load CSS and JavaScript resources specifically for a partial view without it applying to the entire page. Therefore, you'll need to design your page styles or JavaScript to target only the relevant sections.

    <div id="header-section">
        <ul class="menu">
            ...
            <li>@Html.Partial("SearchHeader")</li>
        </ul>
    </div>
    
    ...
    
    <div id="search-header">
        <ul class="menu">...</ul>
    </div>
    

    If I wanted to style the ul.menu differently, I'd use selector rules

    JavaScript

    $("#header-section > .menu").css({ ... });
    $("#search-header > .menu").css({ ... });
    

    Or in a CSS file

    #header-section > .menu { ... }
    #search-header > .menu { ... }
    

    Or just use distinct classes or specific ids

    <div class="header-only"></div>
    <div class="search-header-only"></div>
    <div id="special-item"></div>
    
    .header-only { font-size: 1em; }
    .search-header-only { font-size: 0.85em; }
    #special-item { font-size: 1.5em; }
    
    0 讨论(0)
  • 2021-01-06 13:23

    here is an instruction how to do it. I use express-handlebars with node.js.

    1. create a public folder and put your all folders that include static files in it:css,img,js etc. then add this code to app.js (whatever u named it) to tell express the destination of static files.

      const path = require("path");

      app.use(express.static(path.join(__dirname, "public")));

    2. In express-hndlebars, u should create views folder and inside of it, partials folder. "views/partials" here we keep our partial files. whichever partial u wanna add css , create a css file, "partialName.css" in your css folder. Since u put css folder inside the "public" folder, destination should be like this:

      "public/css/partialName.css"

    add your style in this css file. 3. Linking your style file is very important. Since we gave the destination of public folders to express, express will consider the "public" folder as the root folder. so when you link, it should look like this:

    <link rel="stylesheet" href="css/partialName.css">
    
    1. If you are using bootstrap, to overwrite styling, u should add "!important" at the end of styling line. example:

      .card { width: 100rem !important; }

    0 讨论(0)
  • 2021-01-06 13:32

    The Simplest way which I have done so far,you can provide Url.Content, to all CSS and Script at _Layout page. Hope so it will resolve your query, without much effort. Example

    0 讨论(0)
提交回复
热议问题