views:

82

answers:

4

I don't necessarily need to run it at server, however, I would like to use the ~/js/somefile.js syntax.

Previously, I had just set everything with Absolute paths and set my project to be at the root level. SO, I'd just declare all my stylesheets, background images and javascript files something like /css/somefile.css

However, for this project, it doesn't run as root.

I can't put runat="server" on a script tag.

I can put it on a link tag, though.

This must be a common problem with a few simple answers.

+1  A: 

You can use functions inside the path string, though, e.g.

<script type="text/javascript"
        src="<%=Url.Content("~/Scripts/jquery-1.4.2.min.js") %>"></script>

However that's the ASP.NET MVC syntax for local paths - I can't remember the forms version off the top of my head.

Rup
forms version is the same. MVC syntax is inherited from web forms.
Joel Coehoorn
@Joel I meant the `UrlHelper` class that I'm using is MVC-only. As the others beat me to, the forms version is `ResolveUrl` on `System.Web.UI.Control`.
Rup
+4  A: 

What I've always done is use a normal script tag and put the src in <% %> tags, as illustrated here:

<script language="javascript" src='<%=ResolveUrl("~/App_Themes/MainTheme/jquery.js")%>' type='text/javascript'></script>
David
Thanx! Yes, now I remember seeing this before.
Atømix
Just an FYI, according this post: http://stackoverflow.com/questions/778952/the-controls-collection-cannot-be-modified-because-the-control-contains-code-blo it's better to use # (DataBinding Expression) and Bind from behind.
Atømix
@dl-_-lb: Never saw that before, but it makes sense. Thanks!
David
A: 

Taken from dailycoding.com:

<script language="javascript" src="<%=ResolveUrl("~/[PATH]")%>" type="text/javascript"></script> 
palswim
Haha, beaten by a minute!
palswim
+6  A: 

You can use the ScriptManager for this:

<asp:ScriptManager ID="ScriptManager1" runat="server">
        <Scripts>
            <asp:ScriptReference Path="~/js/somefile.js" />
        </Scripts>
</asp:ScriptManager>
o6tech
I have in the past done this, yes... I wonder what the best way is though. Does this add any other overhead?
Atømix
ScriptManager (or ToolkitManager) is generally the ideal choice in ASP.NET Webforms.
Nathan Taylor
Why is is preferred over ResolveUrl?
Atømix