How to Properly Reference a JavaScript File in an ASP.NET Project? - asp.net

I have some pages that reference javascript files.
The application exists locally in a Virtual Directory, i.e. http://localhost/MyVirtualDirectory/MyPage.aspx
so locally I reference the files as follows:
<script src="/MyVirtualDirectory/Scripts/MyScript.js" type="text/javascript"></script>
The production setup is different though. The application exists as its own web site in production, so I don't need to include the reference to the virtual directory. The problem with this is that I need to modify every file that contains a javascript reference so it looks like the following:
<script src="../Scripts/MyScript.js" type="text/javascript"></script>
I've tried referencing the files this way in my local setup but it doesn't work.
Am I going about this completely wrong? Can somebody tell me what I need to do?
Thanks

Use ResolveUrl("~/")
<script src="<%=ResolveUrl("~/scripts/myscript.js") %>" type="text/javascript"></script>
~/ will get to you the root of your application, virtual or otherwise

Previous answers seem to assume that the Scripts directory always exists as a subdirectory of your application root. If that assumption is correct, and if the page is also at the root, then both of your earlier tags can be simply:
<script src="Scripts/MyScript.js" type="text/javascript"></script>
But my read of your second example is that Scripts isn't always a subdirectory of your application root (because the ../ at the beginning moves up a level, so Scripts would be a peer of your application root). That said, you did say the second example didn't work. :-) But if that's really the case, I'd strongly recommend adjusting one environment or the other so that the relative paths agree, and then always using relative paths as above.
The only reason for using ResolveUrl as far as I know would be if the pages in the application are in a folder structure and the tag may appear in a page at the root or in a page in a "subdirectory". If so, you can use ResolveUrl in both cases so you have an anchor point. I never author things that way, I always ensure I know where the page will be in the hierarchy (if there needs to be a hierarchy) and use an appropriate relative path for the current document.

You can use the HttpRuntime.AppDomainAppVirtualPath property to get the virtual path (if any) for your app and use that to fix up the javascript paths (using <%= ... %> in the <script> tags etc.)
You can further add a global javascript variable in your master page that exposes that value as well, so that any scripts that need to know the actual app root can access it that way.

Another way in MVC5:
1) in the layout html View file, place RenderSection in the place you need the script to be:
<html><body>
#RenderSection("scripts1", required: false)
</body></html>
note that you can change the "Scripts1" to be whatever name you like.
2) in your view html file, just call the "scripts1", doesn't matter where, with your path and js file name:
#Scripts1.Render("~/Scripts/MyScript.js")
3) make sure the MyScript js file is in the Scripts Folder of your project.
That's it.

Related

how do i solve issues regarding external style sheet link which is not in the same directory of the programming file,but works?

I programmed a page (read index.php) including front end and back end operations,and in between i included a link -<link rel="stylesheet" href="style.css" type="text/css">, but there is no effect on the front end application whether I put this css file in the same directory of index.php or delete it. But when I remove the link from the programming page then the front end page is affected. So, how do I conclude this situation? Please anybody help me. I don't understand how the css file works when it is not in the directory where programming page lies.
Based on the information given it sounds like the file is being included from a cache.
Deleting the file on the server wouldn't affect the page render since there is a locally cached version of the file but deleting the link would prevent the browser from loading the cached version.
Sometimes when working on your localhost you have to put the entire path of the CSS file, not just it's normal location as you do when on a live website. Copy your entire path in the href on the link tag and see if it works.
Normally, if the file is in the same place as your index, you put the href the same way it is written in your example above. If your CSS file is in another folder, you would put ../style.css instead. Writing like that, will move up one folder.

CSS and image paths not working

Paths defined within master files are not working on a new server. They worked fine on production server and development machine. Here is an example of the file:
/HeadOffice/Styles/HeadOfficeCalendar.css
Unless I put full URL with the virtual name, the paths don't work.
working:
https://connect.server.co.uk/FesQA/HeadOffice/Styles/HeadOfficeCalendar.css
I can also include resolved URL within ASP>NET code tags but I don't want to change all those paths they are probably hundreds of them. so if the head office folder is in the same folder as master file it should just be able to reference like:
/HeadOffice/Styles/HeadOfficeCalendar.css
It seems the references within the master files and aspx files seems to work fine by adding ~ and runat = server. but images references within the CSS files are not working unless I include the full path.
DOESN'T WORK
url(/HeadOffice/Images/tlcorner.png)
DOES WORK
url(connect.server.co.uk/FesQA/HeadOffice/Images/tlcorner.png)
I know I've answered this before, but this has been known issue forever in VS.
Simple way to do this correctly is to drag the CSS file from Solution Explorer window to head section of master page in code view.
For other links on your site, make sure to include the runat="server" attribute and resolve your links like this (with "~" operator):
<img src="~/images/sample.jpg" runat="server" />

Problem with referencing CSS and JavaScript files relatively

I have an IIS web site. This web site contains other web sites so the structure is like this.
\
MainWebSite\
Scripts\
CSS\
App1\
Scripts\
CSS\
App2\
Scripts\
CSS\
All sites are ASP.NET MVC web applications.
In the MasterPage of App1, I reference the script files like this:
<script type="text/javascript" src="../../Scripts/jquery-ui-1.8.custom.min.js">
</script>
The problem is that it now tries to find the file at http:\server\MainWebSite\Scripts....
How can I work around that? Should I put all my scripts and CSS files into the root directory, is that a preferred solution?
In ASP.NET there is a great function that is part of the Page Object:
ResolveUrl(String)
This is used by passing in a relative string, but the best part is you can use the ~ to symbolize the root of your website:
<script type="text/javascript" src='<%=ResolveURL("~/PATH_FROM_ROOT/Scripts/jquery-ui-1.8.custom.min.js")%>'></script>
[Note the single quotes.]
Try this
<script type="text/javascript" src="~/../Scripts/jquery-ui-1.8.custom.min.js" runat="server"></script>
In the above markup, I'm assuming that your script files are in MainWebSite\Scripts\
"~" brings your reletive reference from your application root directory. The benefit is that if you shift your master page file from MainWebSite\App1\ to MainWebSite\App1\MasterPages\ you will not have to change all the relatively referenced urls in your master page.
The best solution is to use absolute URLs for CSS and JavaScript. Using an appending global variable you can also use it on your development system, too.

Base URL in ASP.net Master Pages with virtual Directories

I have an ASP.net master page. In this master, I have all my css and javascript files defined. I also have a few images and a few buttons and hyperlinks.
All the urls are all declared as relative ie "/scripts/ian.js"
Everything works fine if this site is the root website, but I need it to work in a virtual directory.
My problem is when I place this website in a virtual directory under a root site, all my links are pointing to the root site. so my links point to www.root.com/scripts/ian.js but it should be pointing to www.root.com/virtualDir/scripts/ian.js
I thought the Base Href tag in the header would help, but so far it does not seem to be helping in anyway. All the links are still pointing to the root website when i hover over them.
What I would like is a single setting either in IIS or the config file that I can set a root url and any image, script or link either on the master page or content page, would point to the right place.
Any suggestions or ideas are welcome.
Thanks
All the urls are all declared as
relative ie "/scripts/ian.js"
Those seem to be absolute URL's that you're using, rather than relative URL's, which is probably why the <base /> tag isn't having the desired effect:
This attribute specifies an absolute
URI that acts as the base URI for
resolving relative URIs.
-- from http://www.w3.org/TR/html401/struct/links.html#h-12.4
You could try removing the leading '/' from your URL's to see if that works?
Failing that, I tend to use ResolveClientUrl to get around issues like this, which you'd use in the same way as others have suggested using ResolveUrl:
<script type="text/javascript" src="<%= ResolveClientUrl("~/path/to/js") %>"></script>
...
<img src="<%= ResolveClientUrl("~/path/to/img") %>" alt="..." />
Hope this helps.
Most tags, including regular HTML tags like <link>, <img>, etc can use the ~/ as the application root path if the *'runat="server"' attribute is set.
eg.
<img src="~/images/test.png" runat="server" />
This makes tag a server tag and the tilde is replaced with the application root before the output is returned to the browser.
This doesn't work as expected for the <script> though. When 'runat="server' is set for the script tag, then the script is considered to be server-side javascript and execution is attempted.
To work around this you can either inject the javascript using one of the register client script methods. your you can use the <%= ResolveUrl('~')%> tag in your script tag.
This static method returns you full http path to root folder of your application (web site or virtual directory)
public static string GetAppRootUrl(bool endSlash)
{
string host = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority);
string appRootUrl = HttpContext.Current.Request.ApplicationPath;
if (!appRootUrl.EndsWith("/")) //a virtual
{
appRootUrl += "/";
}
if (!endSlash)
{
appRootUrl = appRootUrl.Substring(0, appRootUrl.Length - 1);
}
return host + appRootUrl;
}
So, you can write in master page:
<script src="<%= Server.HtmlEncode(GetAppRootUrl(false)) %>/scripts/ian.js" language="javascript" type="text/javascript"></script>
Use tilde(~) in yout reference (i.e ~/scrips/ian.js)...see if it works
For links try Page.ResolveUrl in the .aspx page.
So I found this IIS weirdness last night:
<script src="/js/file.js"></script>
Will not work properly in a virtual application that's in a subdirectory of the main IIS site.
Instead, you MUST do it like this:
<script src="/js/file.js" type="text/javascript"></script>
Which is the standard way to do it, but if you're not looking for it, it can surprise you that that additional tag makes the relative path issues go away.

ASP.NET Setting Flash file path for Object tag inside a usercontrol

I have a an ASP.NET user control where i wanto run a flash movie using flashplayer.How can i set the path of flash movie file properly so that this would work in all pages irrespective of the folders. ie; it should work inside a page in FolderA and a page in FolderASub1 which is in FolderA and a page in the Root folder too.My Flash file resides in a Folder called FlashGallery in root.My User control resides in a Subfolder in Root.
I am not sure how can use ~ here .Since its(Object tag to play flash) not a server control.
And infact i cant place the full relative path too.
Anythoughts ?
You can use a root-based path: /FlashGallery/movie.swf
Or you could generate a path string in your code, and place it in the aspx file like this:
Use an absolute path based off the root of your domain. Instead of using a relative url path like
"mymovieplayer.fla"
or
"../mymovieplayer.fla"
do this
"/flash/mymovieplayer.fla"
FYI: I use this (Free)Control: http://www.junasoftware.com/servercontrols/swfobject.net/download.aspx
You can use the '~' tilde to use relative paths to the site root and it will work on a master page, even if content pages are in different directories, you can use it like this:
<%# Register Assembly="SWFObject.Net" Namespace="Juna.Web.UI" TagPrefix="SWF" %>
.
.
.
Its FREEEEE!
Using a root based path is fine if you always know your site will be installed to the root, but this isn't realistic and best practise.
It would've been nice of we could use the server side relative path prefix of ~/ for the ... tag, but as you know it's not a user control so it just gets rendered out to the client as is. Below is a trick to allow you to specify the ~/ relative path for a client side script block.
I essentially use the VirtualPathUtility class and a protected method on the code behind of the page, master page, or control and it works very well for me.
Here's the method:
protected string GetPageRelativePath(string targetPath)
{
return VirtualPathUtility.MakeRelative( Request.AppRelativeCurrentExecutionFilePath, targetPath );
}
And here's how you can use the ~/ prefix in the script block:
<script type="text/javascript" src='<%=GetPageRelativePath("~/Scripts/MyScript.js") %>'></script>
Essentially you could use this with other src paths, even paths to images or Flash files.
Hope that helps.

Resources