Monday, October 7, 2013

URL Routing in ASP.Net Web Forms - Access Script and Image Paths

When we implement URL Routing in Web Forms, one thing that need to be taken into consideration is the path of the images and scripts that need to be assigned to the "src" attribute of the <img> or <script> 

tags. The file source need to be resolved using the ResolveClientUrl() function as explained below:

ILLUSTRATION

Actual ASPX File is in root directory :
~/Home.aspx

The Route Created for Home.aspx:
routeCollection.MapPageRoute("Home", "home/{city}/{area}", "~/Home.aspx", true, new RouteValueDictionary { { "city", "Ahmedabad" }, { "area", "Satellite" } });

Javascript File Location:
~/js/xyz.js

Image file Location:
~/images/abc.jpg

Thus the actual URL displayed will be ~/home/Ahmedabad/Satellite.

But the "src" attribute will always look for the relative path and it will never be able to access the actual file if written in normal way as mentioned above for javascript and image.

Thus, we need to write it as given below:

<script  src='<%= ResolveClientUrl("~/js/xyz.js") %>' />
<img  src='<%= ResolveClientUrl("~/images/abc.jpg") %>' />

The above method will be able to access the actual file from its location.

I hope this blog post is useful for you. Do write your inputs in the comments section.

Thanks & Regards,
Munjal

No comments:

Post a Comment