views:

89

answers:

1

How would I use Ajax do a filtering on a list view in MVC.

Scenario:

List all the news items. To the left is a filter list of categories. Check which categories to show and click the filter button ( or as you check and uncheck it performs the filter ?) to filter the list of new stories.

Here's my View code for iterating the items in the list.

<% foreach (var item in Model)
 { %>
    <div class="newsPreviewContainer">
      <div class="newsTitle">
        <%= Html.ActionLink(Html.Encode(item.Title), "Details", 
                               new { id= item.NewsPostID })%></div>
      <div class="newsBody">
          <%= Html.NewsPreviewBody(item.Body, 250) %></div>
      <div class="newsDate">
          <%= Html.Encode(String.Format("{0:g}", item.DateUpdated)) %></div>
      </div>
  <% } %>

I have created a partial view that lists the categories that each news item can be apart of... Right now it has a submit button that calls an action it uses the formcollection to determine which items are checked. It then takes that list and I do a linq query to get the new list comparing the values that were checked against the news story category value. I return the list to the view and the page reposts with the new result set. This actually all works. I just want to attempt it via AJAX instead. This way the checkboxes shouldnt reset. I would list to actually make this work with out a submit button, basically as the user checks and unchecks a category it does a AJAX call to filter respectively.

Here is my action on submit of the filter button from my partial view...

[AcceptVerbs(HttpVerbs.Post)]
public virtual ActionResult Index(FormCollection fVals)
{
    var q = from x in fVals.AllKeys
            where fVals[x] != "false"
            select x;
    var ids = q.ToList();

    var list = this.newsService.GetNewsPostByGroup(ids);

    return View(list);
}

Ideas and suggestions please, I am working on it as you read this, but I would love any help you could provide.

Thanks so much!

+3  A: 

To start with, you probably want to be able to return only the partialview if the request is made by an AJAX call. This can be done quite easily:

if (Request.IsAjaxRequest())
{
    return PartialView("NewsList", list);
} else {
    return View(list);
}

Or, doing the same thing but in one line:

return (Request.IsAjaxRequest() ? PartialView("NewsList", list) : View(list));

To keep your action method testable without having to mock the HttpContext, you can have the boolean value as an input parameter, which is populated with an attribute. See point 7 in this excellent blog post for details.

Also, for performing the AJAX call on the client side, you might want to use jQuery. Their AJAX API kicks behinds =)

Tomas Lycken
Yea I have some smaller examples I have working with jQuery. I'm trying to figure out how to do the above with it. Thanks for your input!
gmcalab