4

I am trying to get an image from Umbraco in my own class.

I can´t understand why I can not use @umbraco helper in my class. I have its namespace defined in the class, such as:

using Umbraco.Core.Models;
using Umbraco.Web;

I can only use UmbracoHelper, when I write:

var umbracoHelper = new UmbracoHelper(Umbraco.Web.UmbracoContext.Current);

Here is my class:

using Umbraco.Core.Models;
using Umbraco.Web;

namespace House.Site.Helpers
{
    public static class ImageClass
    {
        public static string GetAbsoluteImageUrl(this IPublishedContent node, string propertyName)
        {
            var umbracoHelper = new UmbracoHelper(Umbraco.Web.UmbracoContext.Current);

            var imgID = node.GetPropertyValue<string>("propertyName");
            var imgObject = umbracoHelper.TypedMedia(imgID);

            return imgObject.Url;
        }

    }
}
Claus
  • 1,975
  • 18
  • 24
user1032019
  • 53
  • 1
  • 7

2 Answers2

14

Since your class is not inheriting from any Umbraco base classes you will have to instantiate the UmbracoHelper yourself.

Doing so by using:

var umbracoHelper = new UmbracoHelper(UmbracoContext.Current)

is perfectly fine and will get you access to what you need.

You should be able to use just UmbracoContext.Current instead of the full namespace and class name, since you already have the using statement for Umbraco.Web.

Claus
  • 1,975
  • 18
  • 24
0

Because you need an instance of the helper before you can use it. You have to instantiate it as you have shown because it depends on a valid UmbracoContext which in turn needs a valid HTTP context. When using the helper in your views this has already been taken care of for you and an instance made available via the class your view inherits from.

You can read further details about this in the Umbraco Documentation on Static references to web request instances (such as UmbracoHelper).

ProNotion
  • 3,662
  • 3
  • 21
  • 30