ASP.NET Resource Reference Best Practices - asp.net

I'm relatively new to ASP.NET and was wondering if anyone could shed some light on when I should use relative references (e.g. ../images/banner_tinga.jpg) versus the tilde (e.g. ~/images/banner_tinga.jpg). Depending on the situation you can accomplish the same goal using either. What are the pros and cons of each mechanism? One argument for the relative reference seems to be Visual Studio's design time dislike for resources referenced by the tilde. Whenever I reference a css file that why it indicates it can not be found.
Regards,
javacavaj

The tilde will work only with controls that have runat="server" attribute, and will not work with standard HTML controls. So there's really no universal choice. If you wish to use use tilde with HTML controls you'll have to mark them runat="server", like this
<img src="~/images/myimage.png" runat="server">
But it doesn't seem like a good practice cause it will be added to the viewstate. But then, you can also do this
<img src="~/images/myimage.png" runat="server" EnableViewState="False">
So then the choice becomes truly universal.
Now answering your original question:
I think it's better to use the '~' tilde, because it gives you a point of reference -- the root of your website. The relative path scheme '../' will fail if you change the folder of the webpage and take it to a different level (higher or lower in the hierarchy)
Hope this helped.
To get to your CSS file, do this
<link href="<%= VirtualPathUtility.ToAbsolute("~/css/style.css/") %>" type="text/css">

Hmmm...I disagree with #StevenMcD completely. The tilde always references the root of the web application that you're developing, whereas the relative path notation is based upon your current location within the web application. I think in the long run, if you reorganize or restructure the file locations of the web pages, the tilde notation will make it much easier for you to refactor since you always know that the base path (~) is referring to the root of the web application. You cannot be assured of that if using "../" notation.
One other note...the tilde (~) notation is very handy when using user controls and masterpages in ASP.NET. When you drop in a user control onto a webform, that webform can be nested in any part of your application's file structure. Relative paths simply aren't guaranteed to work in that scenarion. By using the tilde notation, all paths can be written in code and will work because they're based on the root of the web application. Hope this helps.
By the way, the use of the ~ is not deprecated in any way in ASP.NET.
UPDATE: As Cyril mentioned, the ~ is only available to you when using ASP.NET controls. Pure HTML elements won't work with it.

Personally I only use relative references now and avoid the tilde. It may lead to problems further down the line. Although I can't show any reference material connected to it, I remember hearing/reading somewhere that tilde references have been deprecated

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.

Is there a difference between Url.Content("~/...") and "~/" for urls in ASP.NET MVC?

I'm dealing with a web application that resides within a subdirectory on a domain, and I'm attempting to discern the most idiomatic way of inserting a proper URL into an img tag. While the following both produce the same HTML on the client machine, I'm not sure which is more "correct"
<img src="~/Content/images/blah.png" />
<img src="#Url.Content("~/Content/images/blah.png")
Both of these produce an absolute path of /subfolder/Content/images/blah.png, so both work, but I'm curious which one is the right way of doing it.
Is there any difference between these two approaches (for example, is one being resolved by a different mechanism than the other?), or is the former just syntactic sugar for the latter?
With MVC4 you no longer need #Url.Content
If Razor detects ~/ it would created an output identical to
#Url.Content.
http://www.beletsky.net/2012/04/new-in-aspnet-mvc4-razor-changes.html
Nothing is "more correct". I would use the shorthand since Razor now supports it.
if you are passing string through controller, you need to use #url.content().
but it you are passing path directly in .cshtml, no need to use #url.content().
Ex. No need.
<img src="#Url.Content("~/Content/images/blah.png") />
NEED
#ViewBag.ImagePath = "~/Content/images/blah.png";
<img src="#Url.Content(#ViewBag.ImagePath)" />

Seeking global variable to define root url

I have a habit of hardcoding URLs into my HTML:
...logon to your account.
During development when I want to target a specific web-app version I will global search/replace the 'www.mySite' with something like 'myDev.mySite'.
Since this practice has become habitual I can't clearly remember if there's a drop-dead good reason I don't use relative address or if i'm just that persistently dumb.
I would like to think that .net has something similar to the way we define connectionstrings that I could define a root URL as a global variable but so far haven't found the feature.
In ASP.NET MVC, use
<a href='<%=Url.Action("Login")%>'>login</a>
it will automatically generate the URL that works.
<base href> pretty much does exactly what you want.
http://www.w3schools.com/TAGS/tag_base.asp
Jan's answer is the best for ASP.NET MVC, since you can independently change how URLs map to views. A more general solution for any ASP.NET site is by using the tilde. For example,
Page.ResolveClientUrl("~/My/Path.aspx")
Will automatically resolve the ~ to the web application root. Or if you use ASP.NET controls,
<asp:HyperLink runat="server" NavigateUrl="~/My/Path.aspx" Text="Link Text"/>
This will create a hyperlink with the path automatically resolved to the site root.

Theme Image URL Rebasing asp.net

I am implementing themes to enable an existing website to be rebranded (logos, colors, images etc.) depending on the requesting URL. I understand how to do that and have got the skins working fine except for some exceptions related to the URLs of images.
Specifically I have a control property that it is not feasible to skin. Prior to implementing themes it looked like this:
<DisplayImageChecked Url="~/Images/BobIcon-Green.png" />
Obviously that will not work with themes. So after much trial and error and reading I am trying to implement it like this:
<DisplayImageChecked Url="~/AppThemes/<%= Page.Theme %>/Images/BobIcon-Green.png" />
However that does not work. The generated html looks like:
<img src="AppThemes/%3C%25=%20Page.Theme%20%25%3E/Images/BobIcon-Green.png"/>
Any pointers in the right direction would be appreciated.
David
Use the binding syntax inside a databound control (watch the single vs double quotes):
<DisplayImageChecked Url='<%# "~/AppThemes/" + Page.Theme + "/Images/BobIcon-Green.png" %>' />
Is there a reason that you can't just dump the images in the same folder as the theme? If you put an image say for example: "image.gif" into the theme folder, then you can simply refer to it directly in your skin.
ImageUrl="image.gif"
This will resolve just fine when you apply this skin on a control in your page. Also much easier than trying to do the dynamic URL thing.
You may also use "Images/BobIcon-Green.png" as Url. ASP will take care of resolving the Url to the directory within your theme.
Here's the right way to go about your task:
Adorn your property with the UrlProperty attribute, this will tell ASP.NET to automatically translate your partial URL into the proper url.
Using "~/AppThemes/" + Page.Theme + "/Images/BobIcon-Green.png" will do the trick, but it's NOT the preferred way because you need to do all the work yourself and it's always good practice to leave all the work to ASP

Specifying .aspx on the end of a css file?

When working on web apps in ASP.NET, what is the reason for specifying a file as stylesheet.css.aspx rather than just plain stylesheet.css? I have seen this done in various web apps.
The web designer mentioned something about how it's a .NET thing and storing a global variable for the ASPX page but I didn't really understand, nor know the full story.
This is done at my work for a large web app with different sites for different countries. This makes me wonder, when would I make separate web apps for separate countries as opposed to one web app serving different languages? Is there a performance, architectural or other technical reason for doing so? I can think of several non tech reasons (e.g. SEO considerations).
Probably the stylesheet is not static and is dynamically generated on the server.
This technique can be used to provide a different style sheet by considering several parameters (such as user theme selection or something).
Clarification: While you can map .css extension in IIS to be handled by ASP.NET. It has two problems:
Static CSS files will also get handed down to ASP.NET runtime, which will cause a small performance loss.
In many shared hosting environments, you don't have any control on IIS handler mappings.
Web browsers don't care (at least, they shouldn't care) about the extension or anything else about the URL. The only thing they should care about is the Content-Type header. It should be set to text/css; otherwise some of them may complain.
A stylesheet is just a text file - you can specify any file extension you want as long as your <link> matches. In other words this will work:
<link type="text/css" rel="stylesheet" href="style.foobar"/>
as long as your stylesheet has that name. I can't think of any reason for naming the stylesheet with a .aspx extension as it is misleading and confusing. [Other posts have good explanations for why this might be used.]
As mentioned, its to allow the server to process it as an aspx file. It will spit out css I'm sure, but will allow you to do processing server-side.
In the example you gave, if you have the same html content for different regions (perhaps translated, but the same structure), then by having a dynamic css file you can swap out, say, background images. Generally this is considered to be a bad idea, as you should be adding different class names to the html elements to solve this problem.
Another common reason for doing this is to avoid duplication of color definitions. Technically, you can avoid this also by using class names, but it becomes rather annoying. Most people want to have something like:
define sitebordercolor #999;
define sitebackgroundcolor #fff;
and then in their CSS, be able to do:
.foo { border: 1px solid #sitebordercolor; background-color: #sitebackgroundcolor; }
However, CSS doesn't let you do that. So, by using ASPX files, you can achieve the same result:
.foo { border: 1px solid <%=sitebordercolor %>; background-color: <%=sitebackgroundcolor %>; }
If you name a stylesheet .aspx, it will be processed by the ASP.Net engine rather than simply served as a text file.
Once you're in .Net, you are free to write your CSS on the fly. I'd prefer parameterized css.aspx though, since browser want to cache CSS files.
Stylesheets are usually static text files, there's no reason for giving one an .aspx extension unless they are being dynamically generated.
Mehrdad's answer is spot on with regards to the CSS files - that's how we enable dynamic colours on a number of our sites - have the colour defined by a query string, enable page caching varying by that query string, and there you go.
In response to the architecture part of this question:
Whilst SEO considerations would recommend that localised content is often served from a local server and domain (i.e. French content on a .fr domain for example) this often isn't possible.
In terms of maintenance, it's easier to maintain one web site rather than multiple - so you would build it once, take advantage of the framework features to enable localisation (resource files, etc), and then you can either deploy that to one location or multiple as you see fit.

Resources