How to specify virtual path for image in ASP.Net MVC razor helper

35,745

Solution 1

OK, solved it, though I'm not really sure why it's working. After trying all the following combinations without success:

<img src="../Content/images/ajax_activity.gif" alt="loading"/>
<img src="/Content/images/ajax_activity.gif" alt="loading"/>
<img src="~/Content/images/ajax_activity.gif" alt="loading"/>
<img src="Content/images/ajax_activity.gif" alt="loading"/>

the following finally worked as expected

<img src="./Content/images/ajax_activity.gif" alt="loading"/>

It returned the image path correctly with the virtual directory set. Anyone able to explain this?

Solution 2

Try this:

<img src="@Url.Content("~/Content/images/ajax_activity.gif")" alt="loading" />

Solution 3

You could use @Url.Content method to convert virtual relative path to absolute application path like this:

<img [email protected]("~/images/picture.png") alt="picture description">

It'll be converted in this HTML code forwarded to client:

<img src="/appname/images/picture.png" alt="picture description">

UPDATE: In other hand you could convert image to base64 and it will be displayed correctly too:

<img src="data:image/png;base64,iVBORw0KG...SuQmCC" alt="picture description">
Share:
35,745
zszep
Author by

zszep

C# ASP.NET JavaScript react react native python django

Updated on July 09, 2022

Comments

  • zszep
    zszep almost 2 years

    In my razor style helper class (located in the App_Code folder, I've got this line of code:

    <img src="../../Content/images/ajax_activity.gif" alt="loading"/>
    

    This works fine in Cassini, but when I deploy the app to IIS (virtual directory), IIS can't find the path. The virtual path is being ignored. This also doesn't work:

    <img src="@Href("~/Content/images/ajax_activity.gif")" alt="loading" />
    
  • zszep
    zszep about 12 years
    This results in the following compiler error: CS0103: The name 'Url' does not exist in the current context
  • Jordan
    Jordan over 10 years
    This worked for me. Probably more applicable to a broader range of environments.
  • Dan
    Dan over 9 years
    Late reply, but ./Stuff/foo.bar will look in the base directory of the application for Stuff/foo.bar. ~/Stuff/foo.bar corresponds to a virtual path which you presumably did not configure. ../Stuff/foo.bar is a relative path that looks in the parent directory for Stuff/foo.bar. Stuff/foo.bar looks in the current directory, and /Stuff/foo.bar.. well, I can't explain that one. I would have expected that one to also look in the base directory. Stumbled across this while trying to fix similar solution. Point being these can all be different, which is why it might not work.
  • zszep
    zszep over 9 years
    Wouldn't Stuff/foo.bar be the "Stuff subdirectory" in the current directory?
  • Dan
    Dan over 9 years
    Yeah, sorry, I meant Stuff/foo.bar would look in the current directory for Stuff/foo.bar