如何在.ascx中获取图片网址?

时间:2015-04-20 07:43:26

标签: image field sitecore

我在Sitecore中有一个图像字段,我需要它的网址。在后面的代码中我有一个项目:

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

.ascx中,它看起来像这样:

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

我需要将img/bg.jpg替换为项目图片字段的网址。

在转发器中,我通常在后面的代码中有一个方法:

    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 "";
    }

.ascx我称之为:

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

在转发器中使用此方法时,此方法有效。但现在我有一个项目。如何将项目传递给方法以获取其图像URL?还是有另一种方法可以做到这一点吗?

1 个答案:

答案 0 :(得分:1)

您可以在.ascx<%=中使用%>中的代码,这样您就可以执行此操作:

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

您还可以在后面的代码中定义一个方法,直接从您已解决的项目中获取网址:

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

并在.ascx

中调用此方法
<div style="background-image:url(<%= GetBackgroundImageUrl() %>)"></div>
相关问题