我是MVC和软件开发的新手,我想在我的应用程序中实现按日期搜索功能。在索引视图中,我希望用户能够通过网页上提供的两个日期字段进行搜索,"日期"和"订单日期"。目前这是我在视图中的代码,它基本上指定了页面的布局。
using (Html.BeginForm("Index","PurchaseOrder",FormMethod.Get))
{
<p>
Search by Date: @Html.TextBox("searchBy","dateSearchBegin") to: @Html.TextBox("searchBy","dateSearchEnd")
<input type="submit" value="Search" /> <br /><br />
Search by Order Date: @Html.TextBox("searchBy","dateOrderedBegin") to: @Html.TextBox("searchBy","dateOrderedEnd")
<input type="submit" value="Search" />
<br /> <br />
Search by: @Html.RadioButton("searchBy","Requestor", true) Requestor
@Html.RadioButton("searchBy","Vendor") Vendor
@Html.RadioButton("searchBy","workOrder") Work Order # <br />
@Html.TextBox("search","", new { style = "width:10000px" })
<input type="submit" value="Search" />
</p>
}
在控制器中,我有这个代码。这是我试图提供能够按不同字段过滤的逻辑。
// GET: PurchaseOrder
public ActionResult Index(string searchBy, string search, int? page)
{
if (searchBy == "Requestor")
{
return View(db.PurchaseOrders.Where(x => x.Requestor.ToUpper().Contains(search)).OrderBy(i => i.DateOrdered).ToPagedList(page ?? 1, 15));
}
else if (searchBy == "Vendor")
{
return View(db.PurchaseOrders.Where(x => x.Vendor.ToUpper().Contains(search)).OrderBy(i=>i.DateOrdered).ToPagedList(page??1,15));
}
else if (searchBy == "workOrder")
{
return View(db.PurchaseOrders.Where(x => x.PurchaseRequest_.ToUpper().Contains(search)).OrderBy(i => i.DateOrdered).ToPagedList(page ?? 1, 15));
}
else if (searchBy == "dateSearchBegin")
{
return View(db.PurchaseOrders.Where(x => x.Date > "dateSearchBegin" && x.Date < "dateSearchEnd").OrderBy(i => i.Date).ToPagedList(page ?? 1,15));
}
else if (searchBy == "dateSearchEnd")
{
return View(db.PurchaseOrders.Where(x => x.Date > "dateOrderedBegin" && x.Date < "dateOrderedEnd").OrderBy(i => i.Date).ToPagedList(page ?? 1,15));
}
int pageSize = 15;
int pageNumber = (page ?? 1);
pageNumber = page == null ? (ViewBag.pageData == null ? 1 : (int)ViewBag.pageData) : page.Value;
ViewBag.pageData = page;
return View(db.PurchaseOrders.OrderBy(i => i.DateOrdered).ToPagedList(pageNumber, pageSize));
}
我收到一条错误消息,指出&#34;运营商&#39;&lt;&#39;不能应用于类型&#39; System.DateTime?&#39;的操作数?和&#39;字符串&#39;。我该如何解决这个错误,是否有更有效的方法对其进行编码以实现我的目标?
答案 0 :(得分:1)
您需要从查询(DateTime
)构造string search
对象,然后在linq查询中使用它。
var dtFrom = DateTime.Parse(search)
var dtTo ...
return View(db.PurchaseOrders.Where(x => x.Date > dtFrom && x.Date < dtTo).OrderBy(i => i.Date).ToPagedList(page ?? 1,15));
但您还需要引入一次性搜索多个属性的功能。您只需从linq查询中返回IQueryable
并对其进行后续查询即可实现此目的。这样您就可以连接多个查询:
var filtered = db.PurchaseOrders.Where(x => ...).AsQueryable();
filtered = filtered.Where(x => ...).AsQueryable();
等
然后返回
filtered.ToPagedList()