Warm tip: This article is reproduced from stackoverflow.com, please click
asp.net-core-mvc c# linq

How can I filter database results from a Form post?

发布于 2020-03-27 15:45:38

I am pretty certain my lack of understanding is preventing me form getting it to work.

I currently have a form that will post filtering parameters back to the controller, then it will build up the query. The current queries I build does not seam to actually do anything. At least not when it is separated like this.

From what I have read, something like this should work, but from what I have tested, it does not.

public async Task<IActionResult> FilterPost()
    var query = _context.Products;
    query = query.OrderBy(m => m.Unit.Name)
         .Include(m => m.Unit)
         .Include(m => m.Attribute);

    foreach (var request in Request.Form)
         var AttributeValue = request.Value;
         var AttributeName = request.Key;
         query = query.Where(m => m.Attribute.Name == AttributeName)
                      .Where(m => m.Value >= int.Parse(AttributeValue));

    return RedirectToAction("Index");

This method is probably pretty butchered with all the testing I have done on it.

I have looked into using ExpressionTrees and DynamicLINQ before. They do seam confusingly interestring and perhaps a bit overkill, maybe? I dont know. Maybe I my brain is just too exhausted to see the obvious answer...

I would appreciate any kind of suggestion for a solution or a hint towards an solution.

Michał Turczyn 2020-01-31 17:55

Also, set breakpoint and inspect what is inside request. Moreover, you filter data based on request fields, but in each loop iteration you are filtering result more and more, so you have to consider this carefully.

Also, when redirecting to Index, you don't pass any data and I think you should pass result of a query there, so you can use it and show it there. So I'd take look at overloads of RedirectToAction such as RedirectToAction(String, Object). Alternatively, you can take a look at View method with similair capabilities as RedirectToAction.

Having said that, you shuld pass RESULTS of a query, so you need to get the result of a query, for example, by calling ToList method.