Copied to clipboard

Flag this post as spam?

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


  • Dan 1288 posts 3942 karma points c-trib
    May 08, 2012 @ 12:27
    Dan
    0

    Get parent of examine search result with Razor

    Hi,

    I have a razor script which powers a simple website search.  It works fine except some of my content nodes don't have templates associated with them - they're just items in a list.  So when the search finds one of these items I want to link to the parent page and display the whole list of items rather than a link to the node itself which has no template and shouldn't be a 'page' in it's own right.

    The code isn't optimised here, but it should show clearly what I'm trying to do:

    @foreach (var result in ExamineManager.Instance.Search(searchTerm, true)) {
        @if (@result.Fields["nodeTypeAlias"] == "SubPage") {
            <a href="@umbraco.library.NiceUrl(result.Parent.Id)">
                http://@HttpContext.Current.Request.ServerVariables["HTTP_HOST"]@umbraco.library.NiceUrl(result.Parent.Id)
            </a>
        }else{
            <a href="@umbraco.library.NiceUrl(result.Id)">
                http://@HttpContext.Current.Request.ServerVariables["HTTP_HOST"]@umbraco.library.NiceUrl(result.Id)
            </a>
        }
    }

    When the search result is of document type 'SubPage' the link should show the parent of that node, not the node itself.

    The problem is that on saving this I get an error, presumably because the Examine object doesn't store parent data:

    Examine.SearchResult' does not contain a definition for 'Parent' and no extension method 'Parent' accepting a first argument of type 'Examine.SearchResult' could be found (are you missing a using directive or an assembly reference?)

    What's the simplest way to get around this and return the parent URL of the current search result in the loop?

    Thanks folks.

  • Paul Blair 466 posts 731 karma points
    May 08, 2012 @ 13:35
    Paul Blair
    1

    within the for loop you could do something like:

    var node = Model.NodeById(result.Id);

    node.Parent.NiceUrl

    You probably get rid of the if clause as well by using .AncestorsOrSelf(string nodeTypeAlias)

  • This forum is in read-only mode while we transition to the new forum.

    You can continue this topic on the new forum by tapping the "Continue discussion" link below.

Please Sign in or register to post replies