How can I make an MVC lambda filter

2

I'm making a simple filter, and display the data on the page.

The code I'm using is this:

mt.ModelItens = db.Forecast
                  .Where(f => (f.CanalForecast.area == idArea && f.CanalForecast.despesa == idDespesa))
                  .ToPagedList(mt.ModelPaging.page, mt.ModelPaging.pageSizeSelected);

This code works great if the two fields are selected, because if only one is selected it does not show anything.

Referring here:

.Where(f => (f.CanalForecast.area == idArea && f.CanalForecast.despesa == idDespesa))

My problem is that I want it to work by selecting an ex field. (Area) and also works by selecting the two fields (Area and Expense).

I do not know if I was able to get past the real problem.

    
asked by anonymous 15.10.2015 / 16:52

1 answer

2

You'd better target this search by testing what's populated:

var query = db.Forecast;
if (idArea != null) {
    query = query.Where(f => f.CanalForecast.area == idArea);
}

if (idDespesa != null) {
    query = query.Where(f => f.CanalForecast.despesa == idDespesa);
}

mt.ModelItens = query
                .OrderByDescending(entity => entity.idForecast)
                .ToPagedList(mt.ModelPaging.page, mt.ModelPaging.pageSizeSelected);
    
15.10.2015 / 17:19