How can I make a MVC lambda filter

Asked

Viewed 189 times

2

I’m making a simple filter, and show 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 very well if the two fields are selected, because if only one is selected it shows nothing.

Referent 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 by selecting the two fields (Area and Expense).

I don’t know if I got past the real problem now.

  • 1

    Give more information, is missing context, information on how the data are structures and clarity in the objective of the problem and existing doubt.

  • user34200 you registered as Edgar Araujo?

  • I think he came through Oauth in two different ways and didn’t unify users.

1 answer

2

Better you target this search by testing what is filled:

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);
  • Gypsy, Thanks for the help, but that way if I select the two will not have the two filter but only one correct?

  • 2

    It depends on what is filled. If both are, in theory, the two are used as filters. If only one is, only one is used as a filter, and so on.

  • 1

    @Edgararaujo Apparently this user34200 is yours too. Try to unify the logins in your user panel. Incidentally, I changed the response to reflect your code. Thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.