如何使用控制器搜索日期范围?到目前为止,我无法使用下面使用的代码解决它。搜索旅行名称&国家正在努力。 (P.s我是这种编程语言的新手......)提前谢谢你。
public ActionResult Index(string search, DateTime? startdate, DateTime? enddate)
{
if (Session["StaffName"] != null)
{
//original
DateTime str = DateTime.UtcNow;
ViewBag.Datetime = str;
ViewBag.startdate = startdate;
ViewBag.enddate = enddate;
var Trips = from x in db.Trips
select x;
if (search != null)
{
return View(Trips.Where(x => x.TripName.Contains(search) || x.Country.Contains(search) || search == null).ToList());
}
if (startdate != null && enddate != null)
{
return View(Trips.Where(x => startdate > x.startDate && x.endDate < enddate ).ToList());
}
return View(Trips.ToList());
}
}
答案 0 :(得分:0)
您可以使用此修改后的代码...
public ActionResult Index(string search, DateTime? startdate, DateTime? enddate)
{
if (Session["StaffName"] != null)
{
//original
DateTime str = DateTime.UtcNow;
ViewBag.Datetime = str;
ViewBag.startdate = startdate;
ViewBag.enddate = enddate;
var Trips = from x in db.Trips
select x;
if (search != null)
{
if (startdate != null && enddate != null)
{
return View(Trips.Where(x => x.TripName.Contains(search) || x.Country.Contains(search) || search == null && (startdate > x.startDate && x.endDate < enddate)).ToList());
}
else
{
return View(Trips.Where(x => x.TripName.Contains(search) || x.Country.Contains(search) || search == null).ToList());
}
}
if (startdate != null && enddate != null)
{
return View(Trips.Where(x => startdate > x.startDate && x.endDate < enddate)).ToList());
}
return View(Trips.ToList());
}
}
答案 1 :(得分:0)
如果结果评估为if
,则控制器代码中的true
块将返回视图,因此如果search
不是null
,则立即退出方法并且永远不会根据startdate
和/或enddate
值过滤结果。
您需要创建IQueryable<Trips>
并在每个if
块中使用.Where()
子句修改查询,然后在结束时根据过滤后的结果返回视图。
请注意,我假设用户可以在没有startdate
的情况下输入enddate
,反之亦然
public ActionResult Index(string search, DateTime? startdate, DateTime? enddate)
{
ViewBag.Datetime = DateTime.UtcNow;
ViewBag.startdate = startdate;
ViewBag.enddate = enddate;
IQueryable<Trips> trips = db.Trips;
if (search != null)
{
trips = trips.Where(x => x.TripName.Contains(search) || x.Country.Contains(search);
}
if (startdate.HasValue)
{
trips = trips.Where(x => x.startDate > startdate.Value);
}
if (enddate.HasValue)
{
trips = trips.Where(x => x.enddate < enddate.Value);
}
// At this point the query has generated a SQL statement based on the conditions above,
// but it will not be executed until the until the next line - i.e. when calling .ToList()
return View(trips.ToList());
}
注意,不清楚您是否真的想要x => x.startDate > startdate.Value
或x => x.startDate >= startdate.Value
,并且根据您的存储日期是否也包含时间组件,您可能希望使用x => x.startDate > startdate.Value.Date
(同上对于enddate
)
作为旁注,您应该使用视图模型而不是ViewBag
来将值传递给视图。此外,您使用if (Session["StaffName"] != null)
表示您的设计存在问题。