Copied to clipboard

Flag this post as spam?

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


  • Anthony Candaele 1197 posts 2049 karma points
    Jun 28, 2011 @ 16:25
    Anthony Candaele
    0

    implementing Razor search

    Hi,

    I'm implementing search functionality to my website. Therefore I use the Razor code that was provided on FarmCode.org

    @using Examine;

    @
    * Get the search term from query string *@
    @
    {var searchTerm = Request.QueryString["search"];}

    <ul class="search-results">
    @foreach
    (var result in
       
    ExamineManager.Instance.Search(searchTerm, true)) {    
       
       
    <li>
           
    <span>@result.Score</span>
           
    <a href="@umbraco.library.NiceUrl(result.Id)">
                @result.Fields["nodeName"]
           
    </a>        
       
    </li>    
       
    }
    </ul>

    Because the search result output is a bit basic (it only shows the search score and the node name), I would like to extend this code with some extra fields. On my Text Page document type I have a custom property 'pageDescription', so I altered the code to:

    <ul class="search-results">
    @foreach (var result in
        ExamineManager.Instance.Search(searchTerm, true)) {    
       
        <li>
            <span>@result.Score</span>
            <a href="@umbraco.library.NiceUrl(result.Id)">
                @result.Fields["nodeName"]
            </a>
            <span>@result.Fields["pageDescription"]</span>                                                      
        </li>    
       
    }
    </ul>

    But this doesn't work, I get an error like this:

    Error loading Razor Script ExamineSearch.cshtml
    The given key was not present in the dictionary.

    Does someone know what the problem is?

    Thanks for your help,

    Anthony Candaele
    Belgium

  • Dan Diplo 1554 posts 6205 karma points MVP 6x c-trib
    Jun 28, 2011 @ 17:13
    Dan Diplo
    1

    My guess is that only some of your document-types have a pageDescription field. If this is the case, then why you try and access it on a node in your results that doesn't have the property then you get the error. So you need to perform a check first that the key exists. Something like:

    @if (result.Fields.ContainsKey("pageDescription"))
    {
    <span>@result.Fields["pageDescription"]</span>
    }
     

     

  • Anthony Candaele 1197 posts 2049 karma points
    Jun 29, 2011 @ 10:23
    Anthony Candaele
    0

    Hi Dan,

    You where right! Thanks a lot for the help.

    greetings,

    Anthony

Please Sign in or register to post replies

Write your reply to:

Draft