sventevit
sventevit

Reputation: 4816

Url for the asp:Image gets messed up

I am dynamically adding usercontrols to my page:

Method to render my usercontrol:

public static string RenderUserControlAsString(string path)
{
    var page = new PageOverride();
    var viewControl = (UserControl)page.LoadControl(path);
    page.Controls.Add(viewControl);
    var output = new StringWriter();
    HttpContext.Current.Server.Execute(page, output, true);
    return output.ToString();
}

This works OK, but I have problems with ImageUrl of my asp:Image element (my usercontrol contains multiple elements and asp:Image is just one of them):

<asp:Image ID="imgDelete" runat="server" ImageUrl="~/images/delete.gif" onmouseover="this.style.cursor='hand'" onmouseout="this.style.cursor='default'"/>

The ImageUrl gets transformed to ../images/delete.gif, which is not OK. Actially, the ImageUrl always receives two dots and a slash infront of it. Any ideas how to prevent that?

Edit - project structure:

Root:

Upvotes: 2

Views: 524

Answers (2)

sventevit
sventevit

Reputation: 4816

For now I just added an override method to my web control:

protected override void OnPreRender(EventArgs e)
{
      base.OnPreRender(e);

      // Don't use ImageUrl, set fixed src attribute.
      imgDelete.Attributes["src"] = "images/delete.gif";
}

The drawback is, that the image is displayed only on pages, which reside in root folder, but that works for me.

Another way would be with jquery livequery plugin:

$('.Delete').livequery(function () {
    $(this).attr('src', 'images/delete.gif');
});

Edit - I could probably also set CssClass to the image button and set background: url(../images/add.gif) with css...

Upvotes: 0

Software Engineer
Software Engineer

Reputation: 3956

When user control gets added to the aspx webpage, it looks for the images relative to your webpage path, two dots with a forward slash ../ means go back 1 step, in your case it searches for ../images/delete.gif which is invalid for MyPage.aspx as both your web page and images folders are under root.

Either place your user control and webpage in same folder or change the path to images/delete.gif.

Edit: Following hierarchy don't require you to place user control / webpage in same folder or changing path to images folder.

Root:

  • images

    delete.gif ...

  • WebControls

    MyWebControl.ascx ...

  • WebPages

    MyPage.aspx

Upvotes: 1

Related Questions