Grant Thomas
Grant Thomas

Reputation: 45083

ASP.NET Theming Programmatically: Image Paths

We have a multilingual site, or culture-sensitive, and some of the static content now needs to be targeted; for this I'm using themes as it seems the easiest way to achieve what I want, but I can't for the life of me get the images to pick up.

I'm setting the theme in code-behind, and thought at first that maybe this was the issue, but on checking up it looks like I'm doing the right thing (setting on Pre-Init).

I expect to be able to reference images using relative paths where App_Themes/ThemeName/ is automatically resolved, such as:

<asp:Image runat="server" ImageUrl="images\image.jpg"/>

For whatever reason, however, the image isn't being pulled through at all.

This is the code we have in place for setting the theme (the only really relevant part, I'm sure, being the Theme = CurrentSite.CultureName, which is applied successfully):

Private Sub SetTheme()
    Dim themesPath = Server.MapPath("~/App_Themes")
    If Directory.Exists(themesPath) Then
        Dim themePaths = Directory.GetDirectories(themesPath)
        Dim themePathInfo As DirectoryInfo
        For Each _path In themePaths
            themePathInfo = New DirectoryInfo(_path)
            If Not themePathInfo Is Nothing Then
                If themePathInfo.Name = CurrentSite.CultureName Then
                    Theme = CurrentSite.CultureName
                    Exit For
                End If
            End If
        Next
    End If
End Sub

In the above code, CurrentSite.CultureName would be a language culture name (for example, en-gb, or nn-no) that does have an existing corresponding theme folder containing all required resources.

Pages do have EnableTheming set to True. Also, I have tried removing the theme-setting code and applying the theme in the page using Theme="en-gb" to no avail.

Is there anything immediately evident as to why the URLs aren't resolved?

Upvotes: 0

Views: 857

Answers (1)

Josh M.
Josh M.

Reputation: 27801

Use a Skin file to do this. Change your Image tag to:

<asp:Image runat="server" SkinID="SomeImage/>

And in your App_Themes\MyTheme\ folder, add a new Skin file (MyTheme.skin) and add this:

<asp:Image runat="server" SkinID="SomeImage" ImageUrl="images\image.jpg"/>

This image skin now points to image.jpg within the App_Themes\MyTheme\ folder.

For dynamic images you can do this in your BasePage (assuming you have one):

public string ThemePath { get { return "~/App_Themes/" + this.Theme + "/"; } }

public string MapThemePath(string relativePath)
{
    return string.Format("{0}{1}", this.ThemePath, relativePath);
}

But, since I can't see what you're actually doing, I can't say this is the recommended solution. In general your theme contains only things needed or layout and display. You're talking about dynamic images which, to me, doesn't sound like it belongs in a theme? Not sure, just a thought.

Upvotes: 1

Related Questions