views:

146

answers:

1

I am trying to found what is the best practice for view-controller communication for case when I need for example filtering.

I have collection of items on page and filter control. I am filtering items by letter, status, etc... It is straightforward scenario, I am sending filter selected values to controller and controller gives back results to the page.

If you think about it, it is one direction cycle. View call controller with parameters(filter values), controller calls database and then fetch elements and give that elements to the view back. Is there any way to send to controller these elements and controller just to filter them and give filtered collection back to the view? Or maybe to shorten this trip to server, to give controller just id's of elements and controller to know which of elements to pull from database and then to filter them, give filtered collection back...

Bad practice? Some work around?

What do you think?

Thanks

A: 

How I have done this is like what you mentioned in your last parag:

send to controller these elements and controller just to filter them and give filtered collection back to the view

You can use linq to do this. So let's say what you send it a List. So when you execute your filter - let's say by Category - you are expecting a filtered List by Category (let's say Category = "Book").

So in your controller, your List() action (or whatever you call it) should be ready to take a filter parameter. Based on that param then use LINQ to narrow the collection to be passed to the view. Like this:

public ActionResult List(bool fromCache, string filter)
{
    // if filtering - always pull from cache to increase performance
    ProductList productList;
    if (fromCache)
        productList = Session[SessionKeys.ProductList] as ProductList;
    else
    {
        productList = ProductInfoList.GetProductInfoList();
        Session[SessionKeys.ProductInfoList] = productList;
    }

    // apply filter
    var data = productList.Where(p => p.Category == filter);
    return View(ViewLocations.ProductListing, data);
}

The code is may not be syntactically correct but there you go - good luck.

Johannes Setiabudi
nice solution to take these elements from session..in your example, when fromCache variable is false, you pull those elements from db..I simply want to my controller be a filter..to send him elements and to get back them filtered,tnx
Marko