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

Posted by Community Admin on 04-Aug-2018 06:54

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

All Replies

Posted by Community Admin on 09-Oct-2012 00:00

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>

Posted by Community Admin on 11-Oct-2012 00:00

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.

EXAMPLES:

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!

Enjoy

Posted by Community Admin on 07-Oct-2013 00:00

Hi,
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
"\mvc\view\myfolder\index.cshtml"
"\mvc\view\myfolder\index.js"

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

This thread is closed