Filtering the data at the controller before it is rendered in a view

后端 未结 1 665
無奈伤痛
無奈伤痛 2021-01-18 18:08
  1. Hello, I am very new to MVC5, Razor, and EF and I have been looking for two days and still can\'t figure out a solution to my problem.
  2. What
相关标签:
1条回答
  • To keep things simple you can simply add int? Year, int? Qtr, string Div parameters to your Index action and search using them:

    public ActionResult Index(int? Year, int? Qtr, string Div)
    {
        var data= db.JobRecaps.AsQueryable();
        if(Year.HasValue)
            data= data.Where(x=>x.Year == Year);
        if(Qtr.HasValue)
            data= data.Where(x=>x.Qtr == Qtr );
        if(!string.IsNullOrEmpty(Div))
            data= data.Where(x=>x.Div == Div );   
    
        return View(data.ToList());
    }
    

    Note:

    Also you can separate concerns and create a JobRecapSearchModel containing those search parameters and use it as parameter of action and also create a JobRecapBusinessLogic class containing a List<JobRecap> Search(JobRecapSearchModel searchMode) method with the business that I used above. This way you will have a more flexible and beautiful controller.

    To learn more about how to use such method and the benefits you can take a look at this question:

    • Filter/Search using Multiple Fields - ASP.NET MVC
    0 讨论(0)
提交回复
热议问题