Seeking global variable to define root url - asp.net

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.

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)" />

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

How to create friendly url's in asp.net 2

I tried using the IHttpModule and managed to convert the urls just fine,
but all of my images returned path error (all going through the new url directory).
whats the solution?
You need to make sure that you use the "~/" path notation on your images and make sure that they are all server controls with runat='server'. Otherwise the images urls won't get rewritten.
For example if you have a page that gets rewritten from:
/Item/Bicycle.aspx
to
/Item.aspx?id=1234
Then what will happen is that an image reference like this:
<img src='images/something.gif' />
will break. So instead you have to do something like this:
<asp:image imageurl='~/images/something.gif' runat='server' id='img1'/>
Alternatively you can use absolute paths for your images. Or you can push as much as possible into your .css files.
You can try using a URL rewriter such as IIRF.
With IIRF you can use regular expressions to parse the incoming URL as you wish, then send it to the right place.
They have examples built in on how to do all that in the IIRF download.
What's the solution? Use the new routing engine in .NET 3.5 that started in the MVC project and got elevated to stand-alone status. :)
If Keltex's suggestion doesn't solve your specific problem look at ResolveUrl and ResolveClientUrl.

ASP.NET Resource Reference Best Practices

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

Resources