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 12 posts 101 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 1614 posts 7260 karma points MVP 7x 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

  • Comment author was deleted

    Mar 30, 2016 @ 13:39

    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 12 posts 101 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 358 posts 568 karma points
    Dec 03, 2019 @ 14:57
    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