How do you reference .js files located within the View folders from a Page using MVC

By : Vyrotek

For example, if I have a page located in Views/Home/Index.aspx and a JavaScript file located in Views/Home/Index.js, how do you reference this on the aspx page?

The example below doesn't work even though the compiler says the path is correct

<script src="Index.js" type="text/javascript"></script>

The exact same issue has been posted here in more detail:

If this is not currently possible, will it be in the future? If not, how is everyone managing their javascript resources for large MVC projects? Do you just create a folder structure in the Content folder that mirrors your View folder structure? YUCK!

By : Vyrotek


If you re-route your pages to a custom RouteHandler, you can check for existence of files before handling the RequestContext to the MvcHandler class.

Example (not complete):

public class RouteHandler : IRouteHandler
    public IHttpHandler 
    GetHttpHandler(RequestContext requestContext)
        var request = requestContext.HttpContext.Request;

        // Here you should probably make the 'Views' directory appear in the correct place.
        var path = request.MapPath(request.Path); 
        if(File.Exists(path)) {
            // This is internal, you probably should make your own version.
            return new StaticFileHandler(requestContext);
        else {
            return new MvcHandler(requestContext);

For shared javascript resources using the Content folder makes sense. The issue was I was specifically trying to solve was aspx page specific javascript that would never be reused.

I think what I will just have to do is put the aspx page specific javascript right onto the page itself and keep the shared js resources in the Content folder.

By : Vyrotek

This video can help you solving your question :)
By: admin