views:

1456

answers:

4

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: http://forums.asp.net/p/1319380/2619991.aspx

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

+3  A: 

You can use the VirtualPathUtility.ToAbsolute method like below to convert the app relative url of the .js file to an absolute one that can be written to the page:

<script type="text/javascript" src="<%=VirtualPathUtility.ToAbsolute("~/Views/Home/Index.js") %>"></script>
Chris Pietschmann
I tried that and it doesnt seem to work. It generates what I would expect to be the correctly URL but for some reason isnt able to find the js file.
Vyrotek
+1  A: 

You should have separated folder structure for scripts. For example JavaScript folder under application root. Storing js files with views is not only affects you with path resolving issues but also affects security and permissions thins. Also it's much more easier later to embed JS files as assembly resources if you will decide to deploy some of your application parts separately in future when they are stored in dedicated subfolder.

dimarzionist
+1  A: 

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.

Vyrotek
Im looking for the same approach as you. Did you find anything other than stuffing in page or adding to content dir?
Owen
I just hit this same problem today. Completely agree with your "YUCK" in your original post. But putting it onto the page itself is even more yucky I reckon! My first thoughts were that it might be the routing that was preventing js files under the Views folder from being served. Did you have any success at resolving this in the end?
Jonathan Moffatt
+1  A: 

Here's a nice extension method for HtmlHelper:

public static class JavaScriptExtensions
{
    public static string JavaScript(this HtmlHelper html, string source)
    {
        TagBuilder tagBuilder = new TagBuilder("script");
        tagBuilder.Attributes.Add("type", "text/javascript");
        tagBuilder.Attributes.Add("src", VirtualPathUtility.ToAbsolute(source));
        return tagBuilder.ToString(TagRenderMode.Normal);
    }
}

Use it like this:

<%=Html.JavaScript("~/Content/MicrosoftAjax.js")%>