Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Sean Valentine 10 posts 99 karma points
    Mar 30, 2016 @ 13:25
    Sean Valentine
    1

    How do i extend the UmbracoHelper?

    Hi,

    I'm currently experimenting with umbraco and found the Umbraco.NiceUrl(int) helper and wanted to write my own NiceUrl(string) helper.

    So i created the below extension

    public static class UmbracoExtensions
    {
        public static string NiceUrl(this UmbracoHelper helper, string cTypeAlias)
        {
            var node = helper.TypedContentAtRoot().DescendantsOrSelf<IPublishedContent>()
                                .Where(x => x.Name == cTypeAlias).FirstOrDefault();
    
            if (node != null)
            {
                return node.Url;
            }
    
            return "/";
        }
    }
    

    And it works fine if i put a @using at the top of the view.

    My question is how do i get this to automatically be a part of the UmbracoHelper class without using a @using at the top of every view?

    Would it be at application start?

  • Nik 1154 posts 4742 karma points MVP 2x c-trib
    Mar 30, 2016 @ 13:38
    Nik
    103

    Hi Sean,

    You have a couple of options to this really.

    The first (Not recommended but is an option):

    Change the namespace of your extension method to be the same as the UmbracoHelper.

    The second (a much better idea):

    Edit the Web.Config file found in the Views folder. In there you will see a section that looks like this:

      <namespaces>
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Routing" />
        <add namespace="Umbraco.Web" />
        <add namespace="Umbraco.Core" />
        <add namespace="Umbraco.Core.Models" />
        <add namespace="Umbraco.Web.Mvc" />
        <add namespace="umbraco" />
        <add namespace="Examine" />
      </namespaces>
    

    All you need to do is add your namespace into that list and it will be included in all of your views instead of you typing it out all the time.

    Nik

  • Tim Geyssens 6419 posts 15052 karma points MVP 2x c-trib
    Mar 30, 2016 @ 13:39
    Tim Geyssens
    1

    You can place the namespace it in the /views/web.config that way you won't need to place it in each view...

  • Sean Valentine 10 posts 99 karma points
    Mar 30, 2016 @ 13:40
    Sean Valentine
    0

    Thank you both,

    i can't believe i didn't think of that myself. I was trying to be too clever with it all lol.

    Thanks again.

  • Streety 351 posts 559 karma points
    6 days ago
    Streety
    0

    VS2019 doesn't like it. It does compile but shows a bunch of errors.

Please Sign in or register to post replies

Write your reply to:

Draft