Home > Software engineering >  Contains() not working with query string that contains forward slash in ASP.NET MVC app
Contains() not working with query string that contains forward slash in ASP.NET MVC app

Time:07-23

I am trying to implement a search function in my website that can search by date. It is a wildcard search, meaning the user can input anything and it will search multiple fields in the database.

An example URL is testsite.com/Note/SearchNotes?searchquery=6/27. And I have a record in the database with value 6/27/2022 5:44:24 PM in the DateCreated column.

public ActionResult SearchNotes(string searchquery)
{
    var test = db.Notes.Where(Note => Note.DateCreated.ToString().Contains(searchquery) 
    || /* check more properties */).ToList(); //returns 0
}

My problem is it is not returning any data when a query string such as "6/27" contains a forward slash. A string like "27" does return data. I believe / is a legal character, so I can't see why I am facing this problem.

One observation: it may be related to ToString() because forward slashes are returning data on properties that are already of type string.

Could anyone explain the reason for this behavior? Or better yet a solution?

CodePudding user response:

DateTime.TryParse(@"6/27/2022 5:44:24 PM", out var dateCreated);
var notes = new List<string>
{
  @"testsite.com/Note/SearchNotes?searchquery=6/27"
  , @"Some Other Data"
  , @"someOtherNote containing 27..."
  , dateCreated.ToString()
  , dateCreated.ToString("yyyy/MM/dd")
  , dateCreated.ToString("MM/dd/yyyy")
  , dateCreated.ToString("MM/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture)
};
Console.WriteLine("test1");
var test = notes.Where(note => note.Contains("27")).ToList();
foreach (var result in test)
  Console.WriteLine(result);;
Console.WriteLine();
Console.WriteLine("test2");
var test2 = notes.Where(note => note.Contains("/27")).ToList();
foreach (var result in test2)
  Console.WriteLine(result);

produces

test1
testsite.com/Note/SearchNotes?searchquery=6/27
someOtherNote containing 27...
2022-06-27 17:44:24
2022-06-27
06-27-2022
06/27/2022

test2
testsite.com/Note/SearchNotes?searchquery=6/27
06/27/2022

which I think answers your question. DateTime formatting, culture, machine- and user-regional environment settings / localization is all a bit of dark art and to be sure that you find date (parts) by string-matching you must be sure to match format.

Note that even the explicit format "MM/dd/yyyy" produced output formatted "MM-dd-yyyy" until I specified CultureInfo.InvariantCulture

  • Related