Referencing external files in MVC Views

Typically, new developers to ASP.Net MVC get stumped with having to deal with one important fact:  Page.ResolveUrl(...); is missing!!!

Don’t worry or fret – the new way of doing this is:

Url.Content(...);

Some sample usage is as below:

Resolving images:

<img src="<%= Url.Content("~/content/images/myImage.gif") %>" alt="My image" title="My image" />

Resolving JavaScript files:

<script language="javascript" type="text\javascript" src="<%= Url.Content("~/scripts/myscript.js") %>"></script>

Simple as that.

When you refer stylesheet files in your *.Master page, this link is directly reference without needing to use the Url helper as shown above.

So, you can continue refering stylesheet files like:

<link rel="stylesheet" type="text\css" media="screen" href="../content/site.css" />

The MVC framework will resolve the path correctly at run-time.

Hmm.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s