How to perform a search with an interval between one and two dates in Asp.Net Core 2.2

Asked

Viewed 214 times

0

How to perform research with interval between one or two dates in Asp.Net Core 2.2.

I have the following form below containing Start Date and End Date

    @using (Html.BeginForm("Index", "OrdensChegadas", FormMethod.Get))
    {
        <div class="input-group">
            @Html.TextBox("DataInicio", "", new { @class = "form-control", type = "date" })
            @Html.TextBox("DataFinal", "", new { @class = "form-control", type = "date" })
            <span class="input-group-btn">
                <button type="submit" class="btn btn-default"><span class="glyphicon glyphicon-search"></span></button>
            </span>

        </div>
    } 

When I submit the form a Controller can receive the values of Start Date only or Start Date and End Date

In tests I performed only using Datainicio I’m not getting results, noting that I also tried with the condition below:

var applicationDbContext = _context.OrdensChegadas.Include(o => o.GetVeiculo).Where(e => e.Data.ToShortDateString().Equals(DataInicio)).OrderBy(o => o.Ordem);

And so too:

    public async Task<IActionResult> Index(DateTime? DataInicio, DateTime? DataFinal)
    {
        var applicationDbContext = _context.OrdensChegadas.Include(o => o.GetVeiculo).Where(e => e.Data == DataInicio).OrderBy(o => o.Ordem);
        return View(await applicationDbContext.ToListAsync());
    } 

2 answers

1


When I took cases like this it was because in the database I had also saved hh:mm:ss, and from the interface these values came zeroed. To circumvent you can use the . Date of Datetime to eliminate this possibility. Just be careful, that at least one of your dates is nullable.

Where(e => e.Data.Date == DataInicio.Date)

1

Turns out I’m comparing one Datetime with Datetime.Toshortdatestring().

To make comparison, it is necessary to normalize the objects that will be compared.

Try it like this:

var applicationDbContext = _context.OrdensChegadas.Include(o => o.GetVeiculo).Where(e => e.Data.ToShortDateString().Equals(DataInicio.ToShortDateString())).OrderBy(o => o.Ordem);

Recalling that the Dating must be a Datetime not nullable. If nullable, place a validation and after validation, put a .Value, to access the value of the nullable variable.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.