Loading custom CSS files in MVC shared Template RRS feed

  • Question

  • User-195907812 posted

    I need to load CSS files based on the URL structure in to my Views/Shared/_Layout.cshtml view.

    So, if the URL is mywebsite.com/sectiona/partb/page3?id=1234

    I need to insert the following string to the bottom of my <head> section:

    <link rel="stylesheet" href="/css/loadcss/sectiona/partb/page3.csscss/jquery.scrollbar.css">

    I'll obviously check the files exists before I add the string, but I have so many pages this is an easier solution that remembering to reference the CSS from each view page.

    Where would I perform this? I'm learning MVC but there isn't a controller for the template - only views?

    Tuesday, December 11, 2018 1:53 PM


All replies

  • User475983607 posted

    One option is checking the route data.

        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width" />
            if ((string)ViewContext.RouteData.Values["controller"] == "Home")

    Another is dynamically injecting the CSS in the head similar to adding scripts from the View.


    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, December 11, 2018 2:20 PM
  • User-195907812 posted

    Thank you mgebhard :)

    I need this code to execute with every page so I've added a code block (my initial thought was this was bad practice).

    In webforms, I'd just add this to the masterpage's pageload event.

    Anyway, working now - thank you.

    Tuesday, December 11, 2018 2:41 PM