3

This relative and absolute paths always confuse me. i want to know how and where to use them in Asp Net MVC.

For Ex- If i want to use a img tag-

img src="@Url.Content("~/Content/themes/base/images/logo.png")" alt="Koiak Basic Site" />

img src="/Content/themes/base/images/logo.png" alt="Koiak Basic Site"/> 

Kindly explain the difference between both of them

Hasib Tarafder
  • 5,773
  • 3
  • 30
  • 44
Swagat Swain
  • 495
  • 1
  • 4
  • 22

2 Answers2

8

Absolute Path:

An absolute URL path. An absolute URL path is useful if you are referencing resources in another location, such as an external Web site.

<img src="http://www.contoso.com/MyApplication/Images/SampleImage.jpg" />

Relative Path:

A site-root relative path, which is resolved against the site root. Site-root relative paths are useful if you keep resources that are used throughout the site, such as images or client script files, in a folder that is located under the Web site root.

The following example path assumes that an Images folder is located under the Web site root.

<img src="/Images/SampleImage.jpg" />

For More Refer: http://msdn.microsoft.com/en-us/library/ms178116.aspx

Coming to your Question:

<img src="@Url.Content("~/Content/themes/base/images/logo.png")" alt="Koiak Basic Site" />

Here because of using "~".It adds "server" path(i.e; your application path)" to your url. That means it takes img src as "yourapplicationPath/Content/themes/base/images/logo.png"

<img src="/Content/themes/base/images/logo.png" alt="Koiak Basic Site"/>

Here it takes as it is. i.e;"/Content/themes/base/images/logo.png"

For more refer this:

why use @Url.Content

http://digitalzoomstudio.net/2012/04/01/what-is-the-difference-between-absolute-and-relative-paths-urls/

What is the difference between / and ~/ relative paths?

Community
  • 1
  • 1
Ajay
  • 2,022
  • 19
  • 33
1

Absolute Path

In terms of directory

When we refer to a location from root like C:\Documents\MyFolder, it is absolute path.

In terms of URL

Absolute paths are called that because they refer to the very specific location, including the domain name. The absolute path to a web element is also often referred to as the URL. For example, the absolute path to this is:

http://www.stackoverflow.com/posts/21670682

Relative path

In terms of directory

When we refer to a location relative where we currently are, it is called relative path. For example, say currently you are at Documents folder in C:\Documents, to refer to MyFolder you have two choices: Absolute (C:\Documents\MyFolder) or relative (\MyFolder).

In terms of directory

Relative paths change depending upon the page the links are on. There are several rules to creating a link using the relative path:

links in the same directory as the current page have no path information listed

filename

sub-directories are listed without any preceding slashes

weekly/filename

links up one directory are listed as

../filename
Charles Stevens
  • 1,568
  • 15
  • 30