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:


Actual ASPX File is in root directory :

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

Javascript File Location:

Image file Location:

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,

No comments:

Post a Comment