First of all, make sure you're not storing dates as strings. Use
DateTime
in your .NET code, and
one of the date/time types[
^] in SQL - I would suggest
the date
type[
^].
You can either pass your date parameters as strings and use
the DateTime.TryParse
method[
^] to try to convert them to dates; or pass them as nullable
DateTime
values, and rely on model binding to convert them.
Apply only the filters which are defined. Since you want to return records which match all specified filters, that's as simple as using multiple
Where
filters:
[HttpPost]
public async Task<JsonResult> FilterTableA(DateTime? dateStart = null, DateTime? dateEnd = null, string name = null)
{
var records = _context.TableA.AsQueryable();
if (dateStart != null) records = records.Where(r => r.CreatedDate >= dateStart);
if (dateEnd != null) records = records.Where(r => r.UpdatedDate <= dateEnd);
if (!string.IsNullOrEmpty(name)) records = records.Where(r => r.UserName == name);
var result = await records.ToListAsync();
return new JsonResult(result);
}