。NET Core Razor页面中如何按日期搜索?

问题描述 投票:-1回答:1

我首先尝试使用常规的排序和过滤方法来按日期搜索,但它不适用于datetime数据类型,而仅适用于字符串数据类型。如果有人可以帮助我找出如何进行这项工作,那将是很好。另外,我希望将相同的解决方案用于.NET MVC5。为此,我尝试了Search date from the detail asp.Net mvc 5,但是由于某种原因,它对我不起作用。

先谢谢您。

这里是代码:

        //Search by BirthDate
        if (searchStringbyBirthDate != null)
        {
            pageIndex = 1;
        }
        else
        {
            searchStringbyBirthDate = currentFilterBirthDate;
        }
        CurrentFilterBirthDate = searchStringbyBirthDate;

        //Filtering by BirthDate:not working
        if (!string.IsNullOrEmpty(searchStringbyBirthDate))
        {
         personData=personData.Where(b=>b.BirthDate.Equals(searchStringbyBirthDate));
        }

我在这里将其作为字符串,我知道这是错误的,但是我不确定如何在此处提供日期时间。

c# search asp.net-mvc-5 asp.net-core-3.1
1个回答
0
投票

让我们假设您在搜索字符串中提供19/04/2000,并且您正在寻找这一天出生的人。您的人员的生日日期可能带有time(例如19/04/2000 20:30:49 PM)。但是,由于没有提供时间,因此转换为DateTime类型时的搜索字符串将类似于19/04/2000 0:00:00 AM。平等运算运作良好,由于时间原因,这些日期不相等。

因此,如果您只想按日期搜索,则只需比较日期。我在下面创建了一个简单的ASP.NET Core MVC Web应用程序示例。看一下我的示例控制器,如何使用ToShortDateString()方法将两个日期都转换为带有日期的字符串。

示例模型:

public class ExampleModel
{
     public string Name { get; set; }
     public DateTime Date { get; set; }
}

示例控制器:

public class ExampleController : Controller
{
    private IList<ExampleModel> _models = new List<ExampleModel> 
    { 
         new ExampleModel { Name = "Test1", Date = DateTime.Now },
         new ExampleModel { Name = "Test2", Date = DateTime.Now.AddDays(1) },
         new ExampleModel { Name = "Test3", Date = DateTime.Now.AddDays(2) },
         new ExampleModel { Name = "Test4", Date = DateTime.Now.AddDays(3) }
     };

     public ActionResult Index(string search)
     {
        if (!string.IsNullOrEmpty(search))
        {
            if (DateTime.TryParse(search, out var dateTime))
            {
                _models = _models.Where(x => x.Date.ToShortDateString() == dateTime.ToShortDateString()).ToList();
            }
        }

        return View(_models);
    }    
}

示例Index.cshtml:

@model IEnumerable<ExampleModel>

<form asp-action="Index">
    <p>
        Search: <input type="text" name="search">
        <input type="submit" value="Filter" />
    </p>
</form>

<table class="table">
    <thead>
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.Name)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Date)
            </th>
            <th></th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model)
        {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => item.Name)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.Date)
                </td>
            </tr>
        }
    </tbody>
</table>

我也建议您阅读Getting Started with ASP.NET MVC 5教程。

© www.soinside.com 2019 - 2024. All rights reserved.