Copied to clipboard

Flag this post as spam?

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


  • Arno 10 posts 111 karma points
    Sep 09, 2019 @ 12:34
    Arno
    0

    How to build dynamic where clauses?

    Hi there,

    Within a razor template, I have 3 query parameters that can have a value or be empty strings:

    string type = Request["type"] != null ? Request["type"] : "";
    string year = Request["year"] != null ? Request["year"] : "";
    string industry = Request["industry"] != null ? Request["industry"] : "";
    

    And I want to query all the posts that matches these parameters if they are not empty strings.

    So I need to build some dynamic where clauses.

    I have tried a few things but without success. This is how I query my posts now. That would need to be completed with my dynamic where clauses.

    var latestNews = Umbraco.Content(Guid.Parse("24c08a24-217f-4b25-a3e8-df322c4b0d16"))
    .ChildrenOfType("insightsOrNewsPost")
    .Where(x => x.IsVisible())
    

    Anyone has an idea how to do this?

    Thanks

  • Shaishav Karnani from digitallymedia.com 354 posts 1638 karma points
    Sep 09, 2019 @ 12:44
    Shaishav Karnani from digitallymedia.com
    0

    Please can you try below variation:-

    var latestNews = Umbraco.Content(Guid.Parse("24c08a24-217f-4b25-a3e8-df322c4b0d16")) .ChildrenOfType("insightsOrNewsPost") .Where(x => x.IsVisible() && (!string.IsNullOrEmpty(type) || x.type == type) && (!string.IsNullOrEmpty(year) || x.year == year ) && (!string.IsNullOrEmpty(industry) || x.industry == industry ) )

    Cheers,

    Shaishav

  • Arno 10 posts 111 karma points
    Sep 09, 2019 @ 12:58
    Arno
    0

    I've tried with only one parameter like this:

    var latestNews = Umbraco.Content(Guid.Parse("24c08a24-217f-4b25-a3e8-df322c4b0d16"))
    .ChildrenOfType("insightsOrNewsPost")
    .Where(x => x.IsVisible() &&
            x.Id != featuredPost.Id &&
            (!string.IsNullOrEmpty(type) || x.Value<string>("type") == type)
    )
    

    But it returns no results when type is an empty string. And returns all the visible posts without applying the filter when it's not empty.

  • Shaishav Karnani from digitallymedia.com 354 posts 1638 karma points
    Sep 09, 2019 @ 13:05
    Shaishav Karnani from digitallymedia.com
    100

    Hi Arno,

    Please can you try below.

    var latestNews = Umbraco.Content(Guid.Parse("24c08a24-217f-4b25-a3e8-df322c4b0d16"))
    .ChildrenOfType("insightsOrNewsPost")
    .Where(x => x.IsVisible() &&
            x.Id != featuredPost.Id &&
            (string.IsNullOrEmpty(type) || x.Value<string>("type") == type)
    )
    
  • Arno 10 posts 111 karma points
    Sep 09, 2019 @ 13:07
    Arno
    0

    Legend that's the one.

    Thanks a lot for your help !

    Best, Arno

Please Sign in or register to post replies

Write your reply to:

Draft