Mariah
Mariah

Reputation: 727

MVC3 webgrid filtering advice?

I'm trying to figure out the best way (minimal effort) to apply filtering to a webgrid that I have displayed in my Main/Index view (MVC3).

I added a multiselet that would allow filtering by a certain column and I would like to catch the click event (which I already have implemented and working) per select item and then somehow re-invoke my Index() method that contains all the code to rebuild the view based on if it was invoked from a filter (multiselect).

What is the best way to go about this? I know that this is a broad ask but any information would be greatly appreciated.

Thanks!

Upvotes: 0

Views: 1048

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038750

You could place the multiselect inside a form. Then you have 2 possibilities to submit this form:

  1. Using a submit button
  2. Using the onchange event of the multiselect (in this case you will have to use javascript)

The first point is straightforward:

@using (Html.BeginForm())
{
    @Html.ListBoxFor(x => x.SelectedItems, Model.Items)
    <button type="submit">Filter</button>
}

To implement the second you could use jQuery and subscribe to the change event of the multiselect. First, let's give this multiselect an id so that we can more easily select it:

@using (Html.BeginForm())
{
    @Html.ListBoxFor(x => x.SelectedItems, Model.Items, new { id = "filter" })
}

and then in a separate javascript file:

$(function() {
    $('#filter').change(function() {
        // when the selection changes we manually trigger the submission
        // of the containing form
        $(this).closest('form').submit();
    });
});

In both cases the controller action that we are submitting to will take an array of strings as argument which will represent the selected values in the multiselect which will be used to filter the resultset.

Upvotes: 1

Related Questions