'How to filter data in model in ActionResult of controller in ASP.net core MVC?

I have an index.chtml set up with about 10 ActionLinks. Those actionLinks trigger different ActionResult functions within the controller since each of them essentially perform unique queries on a data model.

I also have an entities object named db which has all the data. Instead of just displaying all the data, I want to perform complex filtering on the entities object to find where certain properties of records are null or where a property is greater than some input then returns a view of all columns on only those records that were filtered.

Find nulls:

public class printJobsController : Controller {
  private PrintJobsEntities db = new PrintJobsEntities
  public ActionResult IncompleteJobs {
    //get jobs where processDate is null
    ...
  }
}

Find where count is greater than 10:

public class printJobsController : Controller {
  private PrintJobsEntities db = new PrintJobsEntities
  public ActionResult JobsGreaterThan(int limit) {
    //group by printerName and find counts greater than limit
    ...
  }
}

How do I go about doing this?



Solution 1:[1]

Seems you are trying to populate the View with filtered data as per your request parameter in controller action.

You could follow the below steps to achieve what you are trying to:

Your imaginary Data Model

public class PrinterJob
     {
                    [Key]
                    public int PrinterId { get; set; }
                    public string PrinterName { get; set; }
                    public int PrintedBy { get; set; }
                    public int TotalPrint { get; set; }
            
     }

Sample Data In Database:

enter image description here

Controller Action:

   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);

    }

Output After Applying Filter:

enter image description here

Note: Here I am trying to filter printer information which printed more then 30 printing jobs.

Hope it would help you to achieve your goal. If you still have any problem feel free to let me know.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 CaptainGenesisX