More in this section

Forums / Developing with Sitefinity / Where to store MVC widget CSS and Javascript and how to link it

Where to store MVC widget CSS and Javascript and how to link it

3 posts, 0 answered
  1. John
    John avatar
    1 posts
    08 Oct 2012
    09 Oct 2012
    Link to this post
    What is the best practice for storing CSS and JS for MVC widgets?

    For example I have all my MVC widgets under the /Mvc directory which then breaks down to Controllers, Models, Views

    I want to use a new CSS or JS file for my widget. I am currently copying and pasting all the the CSS and JS content directly into my view's .cshtml which is not ideal at all.

    Where should I store the CSS/JS files, and how would I link them from my view?

    I was thinking something like this structure might work, where I would have a 'widgets' directory on the same level as the Mvc directory:

    /widgets/widget-X/css and /widgets/widget-X/javascript
    /widgets/widget-Y/css and /widgets/widget-Y/javascript

    Or would it be better to create the css and js directories inside the actual view's directory?

    Using that how would I link them from my view. I suppose I would need some sort of variable containing the site HTTP root like:

    <script type="text/javascript" src="@SiteRoot/widgets/widget-X/css/main.js"></script>
  2. Ryan
    Ryan avatar
    2 posts
    16 Jul 2012
    11 Oct 2012
    Link to this post
    You can store your css and javascript files anywhere. I usually store all my css and javascript in their own folders in the project root. 

    In terms of linking your stylesheets and scripts from your view, it's fairly simple.

    You will use some razor here. @Url.Content("")

    Inside of the quotations, start with ~/ this notates you're starting from the root, then drill down your folders after that.


    CSS: <link type="text/css" rel="stylesheet" href="@Url.Content("~/css/stylesheet.css")" />

    JAVASCRIPT: <script type="text/javascript" src="@Url.Content("~/scripts/jscript.js")"></script>

    This should work!

  3. Hywel
    Hywel avatar
    11 posts
    04 Sep 2013
    07 Oct 2013
    Link to this post
    For reasons I wont go into, I really need to use "proper" relative links to my JS.
    I have put the js in the same folder as the view, so I have

    I am then trying to add the js to the cshtml using
    "<script src="index.js" type="text/javascript"></script>"

    Unfortunately this does not add the script.
    If I use:
    "<script src="~/Mvc/Views/myfolder/index.js" type="text/javascript"></script>"

    It does work, but as I said I need to be able to use relative paths....

    Any help on this would be greatly apprecieated

3 posts, 0 answered