mark_da_rat
mark_da_rat

Reputation: 61

How to pass a predicate as parameter into IActionResult in ASP.NET MVC

I want to refactor my huge messy code and am stuck. I have an IActionResult Index which makes a simple Select on a Table. Later I added two different searchpanels, which are pretty complicated and were inside the Index. I used PredicateBuilder for that. Now I have excluded them from my Index and put them in two separate IActionResults, which are called by the user:

public async Task<IActionResult> Index(Func<model,bool> predicate)
    {
        IQueryable<model> SQL;
        SQL = from m in _context.model
              select m;
        if(predicate != null)
            SQL = (IQueryable<model>)SQL.Where(predicate);

        return View(await SQL.ToListAsync());
    }

public IActionResult Search1(Parameters parameters)
    {
        var predicate = PredicateBuilder.New<model>();

        predicate = predicate.And(s => s.Number1 == parameters.Number1);
        predicate = predicate.And(s => s.Number2 >= parameters.Number2);
        ...
        
        return RedirectToAction(nameof(Index), new { predicate = predicate });
    }

public IActionResult Search2(string searchString)
    {
        var predicate = PredicateBuilder.New<model>();

        predicate = predicate.And(s => s.publisher1.Contains(searchString.Trim()) || s.publisher2.Contains(searchString.Trim());
        ...
        
        return RedirectToAction(nameof(Index), new { predicate = predicate });
    }

The problem is, that when I go now to my Index Page, the Homepage simply doesn't work anymore. As soon as I remove Func<model,bool> predicate as parameter the Homepage runs as usual. So does that way not work in general, or did I do something wrong?

Thanks very much for your help!

Upvotes: 0

Views: 379

Answers (0)

Related Questions