PassionateDeveloper
PassionateDeveloper

Reputation: 15148

Image URL in a ASP.Net Page

I have a default image in my folder in visual studio.

How can I get the server path to find the image in runtime in code?

if (String.IsNullOrEmpty(entry.Picture))
{
    //image1.ImageUrl = @"F:\Temp\Projects\IMEICHECK\IMEICHECK\Images\Design\New\no-image.gif";
}
else
    image1.ImageUrl = entry.Picture;

Upvotes: 0

Views: 1125

Answers (2)

bugventure
bugventure

Reputation: 498

Server.MapPath("~/Images/Design/New/no-image.gif") would give you the absolute path of the image on the server. However, it seems you need the resource URL to use for an image element on your page. In this case, you may want to use Page.ResolveClientUrl("~/Images/Design/New/no-image.gif") which will give you an absolute URL you could set as the src of an image HTML element. But even simpler, you are using a server-side Image control, so passing the relative image url ("~/Images/Design/New/no-image.gif") would suffice.

Upvotes: 0

KP.
KP.

Reputation: 13720

It looks as though perhaps your image path is not part of the website or web application. This is not good practice.

You should put the image in a common location within the web app/site, such as:

/Common/Images/no-image.gif

And then easily store that path either in the web.config appSettings section, or as a constant string in your code-behind if it's only used in one place.

private const string defaultNoImagePath = "/Common/Images/no-image.gif";

if (string.IsNullOrEmpty(entry.Picture))
{
    image1.ImageUrl = defaultNoImagePath;
}
else
{
    image1.ImageUrl = entry.Picture;
}

Upvotes: 1

Related Questions