Have an Action method in your Controller
. Using reflection you can read the resourceName and return it as FileStreamResult
. In the view add script path as /Controller/Action/actualjsfile.js
Refer to this Blog Post as well
Steps on tested sample as follows
Create class library project (JSDLL)
add TestJS.js
as embedded resource (file contents as shown below)
function MyAlert() {
alert("Hello! this is from the dll");
}
In AssemblyInfo.cs add the following (need to add reference to System.Web.dll)
[assembly: System.Web.UI.WebResource("JSDLL.TestJS.js", "application/x-javascript")]
Compile class library project and add as reference to your MVC project
In your controller add the following action (same as the blog post; but with minor modifications)
public FileStreamResult ContentFile(string id)
{
string resourceName = Assembly.GetAssembly(typeof(JSDLL.Class1)).GetManifestResourceNames().ToList().FirstOrDefault(f => f.EndsWith(id));
return new FileStreamResult(Assembly.GetAssembly(typeof(JSDLL.Class1)).GetManifestResourceStream(resourceName), "text/javascript");
}
Simple View to test (have a look at how the .js
file is referenced. onClick
I am calling the function from the .js
file)
@{
ViewBag.Title = "About Us";
}
<h2>About</h2>
<p>
Put content here.
<button type="button" onclick="MyAlert()">Text</button>
</p>
<script type="text/javascript" src="/Home/ContentFile/TestJS.js"/>
output

EDITED (for Matthew's comment)
here are few screen shots





