Search code examples
master-pages

Runat server or ResolveUrl : Which one is more efficient / preferable and why?


I have two options to make the images work fine in root as well as sub directories when placed in a Master page in ASP.NET. Both the ways works fine for me but I need to know which option is more preferable from bandwidth perspective. Is there a major difference between these two?

Below is the first option wherein I am using the "runat=""server"" option:

  <img src="images/twitter-bird.png" alt="" class="image_left1" >

Below is the second option wherein I am using the "ResolveUrl("~")" option:

 <img src="<%= ResolveUrl("~") %>images/twitter-bird.png" alt="" class="image_left1" >

Solution

  • "Runat server" and ResolveURL are two very different things and aren't related that way.

    Runat tells asp.net to make the control a server side control which you then can access from your code behind to do various things to it. This means you can use the control, add stuff to it, add new user controls or what ever. This is basically at the core of webforms in asp.net.

    ResolveURL is a function that returns the relative path to a resource. The ~ then tells it to look from the "root" of the website. This is usable because your control tree (page -> usercontrols -> usercontrols) can quickly become quite deep but often uses resources like graphics from a single folder, so if you don't make your paths relative from the root of the website, you'll most likely end up with broken links.

    In your example there are multiple ways to do it and it depends on situation. If it is a static graphics that never changes - it could just as well go in your CSS with a relative path from there and then you'd need not worry.
    If it is dynamic image - meaning it can change depending on context then I'd make the image html tag into an asp:image (runat server), and then in the codebehind set the image url using ResolveURL()