Home > Blockchain >  How to Format Search String to Return Part of Search String From More Than One Column in Razor Page
How to Format Search String to Return Part of Search String From More Than One Column in Razor Page

Time:12-31

I have a data table that I would like to filter via a Search box on my razor page.

Here is my current code:

        if (!String.IsNullOrEmpty(searchString))
            referral = referral.Where(s => s.BoardMtgMonth.Contains(searchString) || s.BoardMtgYear.Contains(searchString));

So, one column in the table (BoardMtgMonth) has month values: January, February, March, etc The other column (BoardMtgYear) has year values: 2013, 2014, 2020, etc

I need to make my search return values for a pairing of those 2 values. If a user types in March 2020, I would like all rows from the table that have a BoardMtgMonth value of March AND a BoardMtgYear value of 2020 to be the search result.

Right now, If I type in March: I get all rows that have a March month. If I type in 2020: I get all rows that have 2020 for their year. If I type in March 2020: I get NO returned values.

How do I change the format of my Search String so that it accepts an AND combination search? Ie, BoardMtgMonth = March AND BoardMtgYear = 2020? Is there something other than the 2 pipes || I should be using?

Thanks for any and all assistance.

CodePudding user response:

Modify your search string to include both values separated by a delimiter, such as a space character. You can then use the Split method to split the search string into an array of strings, and use the Contains method to check if the values in the table match the values in the search string.

if (!String.IsNullOrEmpty(searchString))
{
    string[] searchValues = searchString.Split(' ');
    referral = referral.Where(s => s.BoardMtgMonth.Contains(searchValues[0]) && s.BoardMtgYear.Contains(searchValues[1]));
}

The Where checks if the BoardMtgMonth column contains the first value (=> month value) AND the BoardMtgYear column contains the second value in the searchValues array (=> year value).

As Example January 2023 will split into January and 2023.

if (!String.IsNullOrEmpty(searchString))
{
    string[] searchValues = searchString.Split(' ');
    if (searchValues.Length == 1)
    {
        referral = referral.Where(s => s.BoardMtgMonth.Contains(searchValues[0]) || s.BoardMtgYear.Contains(searchValues[0]));
    }
    else
    {
        referral = referral.Where(s => s.BoardMtgMonth.Contains(searchValues[0]) && s.BoardMtgYear.Contains(searchValues[1]));
    }
}

This would combine the single and multi value search.

  • Related