asp.net-core - 如何在 ASP.net core MVC 控制器的 ActionResult 中过滤模型中的数据?
问题描述
我有一个 index.chtml 设置了大约 10 ActionLinks
。这些actionLinks
触发ActionResult
控制器内的不同功能,因为它们中的每一个本质上都对数据模型执行独特的查询。
我还有一个名为 db 的实体对象,其中包含所有数据。我想对实体对象执行复杂的过滤,而不是只显示所有数据,以查找记录的某些属性为空或某个属性大于某个输入的位置,然后仅返回那些被过滤的记录上的所有列的视图.
查找空值:
public class printJobsController : Controller {
private PrintJobsEntities db = new PrintJobsEntities
public ActionResult IncompleteJobs {
//get jobs where processDate is null
...
}
}
查找 count 大于 10 的位置:
public class printJobsController : Controller {
private PrintJobsEntities db = new PrintJobsEntities
public ActionResult JobsGreaterThan(int limit) {
//group by printerName and find counts greater than limit
...
}
}
我该怎么做呢?
解决方案
似乎您正在尝试根据View
控制器操作中的请求参数填充过滤后的数据。
您可以按照以下步骤来实现您的目标:
你想象中的数据模型
public class PrinterJob
{
[Key]
public int PrinterId { get; set; }
public string PrinterName { get; set; }
public int PrintedBy { get; set; }
public int TotalPrint { get; set; }
}
数据库中的示例数据:
控制器动作:
public ActionResult <PrinterJob> JobsGreaterThan(int limit) {
var printCountByGroup =
(from objPrint in _context.PrinterJobs group objPrint by new {
objPrint.PrinterName, objPrint.PrintedBy, objPrint.TotalPrint
}
into grp where grp.Sum(p => p.TotalPrint) > limit
select new {
PrinterName = grp.Key.PrinterName, PrintedBy = grp.Key.PrintedBy,
TotalPrint = grp.Key.TotalPrint
});
return View(printCountByGroup);
}
应用过滤器后的输出:
注意:这里我试图过滤打印超过 30 个打印作业的打印机信息。
希望它会帮助你实现你的目标。如果您仍有任何问题,请随时告诉我。