I looked at this tutorial for creating a javascript that is used withing several projects in the same solution. Basically, I created a class Library where I have a script folder in which I create a script file which I want to use in several projects within the same solution.
In the script folder of the projects which use the commonscript file, I added an existng item as described in the link above. I added the file as a link and not a copy of the file. However, my view s not able to read this javascript file.
I even add this command to the pre-build event for project using the javascript so I could copy the file from the classlibrary to my project during before building but did did not work either.
copy $(SolutionDir)ClassLibraryName\Scripts\CommonScript.js* $(ProjectDir)Scripts\CommonScript.js
and added the script to my view
<script src="@Url.Content("~/Scripts/CommonScript.js")" type="text/javascript"></script>
How can I create a javascript file and use it in several projects in the same solution
You might also consider restructuring your application to use areas rather than using two fully separate projects. I've had the most success using multiple projects only for fully separate parts of the application (i.e. interfaces in one project, models in another, class definitions in a third, areas, controllers, and views in a fourth). If you use areas, then your views can pull from the same set of resources (such as Content and Script folders).
The other alternative is to have a "media server" or "static asset server" which is separate from your web sites. This could just be another virtual directory in IIS that could contain any static assets, like JavaScript, CSS or images. Then you would need to reference those assets properly from your MVC projects:
<script type="text/javascript" src="/assets/foo.js"></script>
You can still utilize relative URLs if the static asset virtual directory is on the same server. I might suggest this setup for IIS:
Since the "assets" virtual directory is just a folder with files, you wouldn't even need to create a Visual Studio project for it. Using a text editor like Sublime Text would suffice, since it can open up a folder and present it like a project.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With