SpaceJump
SpaceJump

Reputation: 483

How to get image url in .ascx?

I have an image field in Sitecore from which I need its url. In code behind I have one item:

Item contactSlide = itemHelper.GetItemByPath("/sitecore/content/AMM/Resources/Slides/Slide Contact");

In the .ascx it looks like this:

<div class="contact-section grid-padding-big" style="background-image: url(img/bg.jpg)">

I need to replace img/bg.jpg with the url of the image field of the item.

In repeaters I normally have a method in the code behind for this:

    public string GetImageUrl(Item item)
    {
        Sitecore.Data.Fields.ImageField imgField = ((Sitecore.Data.Fields.ImageField)item.Fields["Bild"]);
        if (imgField.MediaItem != null)
        {
            string mediaUrl = Sitecore.Resources.Media.MediaManager.GetMediaUrl(imgField.MediaItem);
            return mediaUrl;
        }
        return "";
    }

And in the .ascx I call it like this:

<div style="background-image:url(<%# GetImageUrl((Sitecore.Data.Items.Item) Container.DataItem) %>)"></div>

This works when using this method while in repeaters. But now I have a single item. How can I pass the item to the method to get its image url? Or is there another way to do this?

Upvotes: 2

Views: 1097

Answers (1)

Kevin Brechb&#252;hl
Kevin Brechb&#252;hl

Reputation: 4727

You can use code in a .ascx within <%= and %>, so you could simply do this:

<div style="background-image:url(<%= GetImageUrl(itemHelper.GetItemByPath("/sitecore/content/AMM/Resources/Slides/Slide Contact")) %>)"></div>

You can also define a method in your code behind to directly get the url from the item you have already resolved:

public string GetBackgroundImageUrl()
{
   Item contactSlide = itemHelper.GetItemByPath("/sitecore/content/AMM/Resources/Slides/Slide Contact");
   return this.GetImageUrl(contactSlide);
}

And call this in the .ascx:

<div style="background-image:url(<%= GetBackgroundImageUrl() %>)"></div>

Upvotes: 1

Related Questions