ASP.NET MVC 5 中两个日期之间的高级搜索

Advanced search between two dates in ASP.NET MVC 5

我使用此代码进行高级搜索

public ActionResult AdvanceSearch(string HeadTitle, string fulltext, string firstdate, string enddate, string newstype)
    {
        var q = db.Tbl_News.Where(n => n.HeadTitle.Contains(HeadTitle) && n.FullText.Contains(fulltext) && n.Date >= firstdate && n.Date <= enddate);
        return PartialView("AdvanceSearch", q);
    }

此代码适用于在 HeadTitle 和全文中搜索,但当我添加日期时显示错误。

如何使用此代码在两个日期之间进行搜索?

首先,你的日期参数应该是DateTime类型, 我建议将您的代码更新为

var q = db.Tbl_News
            .Where (n => n.HeadTitle.Contains(HeadTitle) 
            .Where (n => n.FullText.Contains(fulltext)) 
            .Where (n => n.Date >= firstdate.Date )
            .Where (n => n.Date <= enddate.Date);

为了更具可读性,只比较日期部分(忽略时间)

如果不想改变参数类型,这样也可以。

public ActionResult AdvanceSearch(string HeadTitle, string fulltext, string firstdate, string enddate, string newstype)
{
    var q = db.Tbl_News
        .Where (n => n.HeadTitle.Contains(HeadTitle) 
        .Where (n => n.FullText.Contains(fulltext)) 
        .Where (n => n.Date >= DateTime.ParseExact(firstdate, "MM/dd/yyyy", CultureInfo.InvariantCulture))
        .Where (n => n.Date <= DateTime.ParseExact(enddate, "MM/dd/yyyy", CultureInfo.InvariantCulture));
}