Link relative to Application root with client tag - asp.net

Is there any way to link to the application root with the ~ character (or something similar) in a client tag (e.g. <link>)? I have some external stylesheets and scripts that I need to link to in a Master page, but I don't want to hardcode the path relative to the IIS site, I want to do it based on the relative application path.

Yes, use <link href="<%= ResolveUrl("~/meep/moop.css") %>" />.
Not the prettiest of solutions, but you should only use it a couple of times during development...

Rather than invoke ResolveUrl method, you could simply include the tilde and the runat attribute as follows:
My Link
This will resolve from the root always.

Related

Understanding a url that references a CSS file in a SharePoint master page

For SharePoint, this is the entry you could put into your master page to link to a CSS file.
<SharePoint:CssRegistration
name="<% $SPUrl:~sitecollection/_catalogs/masterpage/dir/file.css %>"
runat="server"
after="SharepointCssFile"/>
Could someone please break down the pieces of this url? I don't understand the following parts of it and how they work together:
<% - I do know this means less than
$SPUrl:~sitecollection/ - Is this some kind of variable? What's ~ for?
%> - I do know this means greater than
CssRegistration is just one of the many ways of referencing CSS files in
SharePoint.
lower than (<) and greater than (>) obvious, and ~ refers to the root of the current web application.
CssRegistration is particularly interesting because you can use After to make sure your CSS is loaded after another CSS such as core.css
The real relevant parameter is name, which in this tag can be used with SPURL, which in turn can be used with sitecollection or site, to refer to the current sitecollection root, or just the current site/web.
Note that SPURL is only available on SharePoint Server, not Foundation.
To support Foundation you can use ProjectProperty, which takes Url or SiteUrl.
So to wrap up, SPUrl is a token available in SharePoint that we can use to specify a resource from a specific location, relative to the current page, web, site and others.

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

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.

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.

How do I handle file paths in my code before moving to server host?

In my webpages I have references to js and images as such:
"../../Content/Images/"Filename"
In my code if I reference a file as above, it doesnt work so i have to write:
"c:/miscfiles/"filename"
1-Why does the first reference work on webpages and not within the code?
2-How should i reference file paths in code so that I will not have to recode when moving to server?
See following for more details:
http://msdn.microsoft.com/en-us/library/ms178116.aspx
Don't use absolute paths in development - always use relative paths that are preceded with the application root token (the tilde or ~) like this:
"~/Content/Images/Filename"
ASP.NET will convert the ~ to the proper value based on the virtual directory or website the code is hosted in.
For ASP.NET 2.0 onwards, in order to get the tilda (~) syntax to resolve correctly on the server, you have to include a title and a runat attribute as follows:
<img src="~/images/image.jpg" title="Image" runat="server" />
The presence of the runat attribute ensures that the path is resolved on the server.

Resources