Sunday, May 9, 2010

Master page image path problem in asp.net C#

As you knew that master page uses absolute image URL which cause problem to reference an image inside other folder. The problem occurs due to below reasons:

1. Master page is in the root folder
2. Images under another root folder
3. Aspx pages under another root folder

As a result you will get "Image not found" or "Image file path not exist" error.

Scenarios like below will help you to understand the problem:
Master Page

To set the master page image path to reference an image based on above scenario you may write a code like:
<img alt="" src="Images/netmixerfinal.gif"/>

Which will creating the problem. The solution is simple and you may follow the below code to resolve the problem:
<img alt="" src="<%= Page.ResolveUrl("~")%>Images/netmixerfinal.gif"/>

If you not yet understand the problem then continue to read to run an example.
First add a master page then add a folder named images also add a folder named CRMModule. Now put an image under images folder plus add an aspx page(must include previously defined master page) under CRMModule folder.

Now modify the masterpage code like below:
<%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="MasterPage" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Master page Image path problem</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <img alt="" src="<%= Page.ResolveUrl("~")%>Images/netmixerfinal.gif"/>
        <hr />
        <asp:contentplaceholder id="ContentPlaceHolder1" runat="server">
        </asp:contentplaceholder>
    </div>
    </form>
</body>
</html>

Now add a label in the container page and write something on it.
Now run the project and you will get something like below:

Master Page Output

Hope now referencing image path from master page has been resolved.

6 comments:

  1. Thanks buddy that's give for information about .net I think .Net mostly website has using that .Net program. ASP.Net Application Development

    ReplyDelete
  2. Thank you!, it was my problem today, but i resolved it with your post.

    Thanks again

    Aldo

    ReplyDelete
  3. thanx bro. its working for me

    ReplyDelete
  4. hai,

    thanks for the information..thanks a lot

    ReplyDelete
  5. thanks a lot !!!! works for a complex folder straucture too

    ReplyDelete
  6. Thank you .The image is now working at all pages

    ReplyDelete

Write your Comment: