Doug.Instance

Improving the world one post at a time
posts - 22 , comments - 47 , trackbacks - 0

Simple Interactive Search with jQuery and ASP.Net MVC

Google now has a feature where the search updates as you type in the search box.  You can implement the same feature in your MVC site with a little jQuery and MVC Ajax.  Here's how:

  1. Create a javascript global variable to hold the previous value of your search box.
  2. Use setTimeout to check to see if the search box has changed after some interval.  (Note: Don't use setInterval since we don't want to have to turn the timer off while Ajax is processing.)
  3. Submit the form if the value is changed.
  4. Set the update target to display your results.
  5. Set the on success callback to "start" the timer again.  This, along with step 2 above will make sure that you don't sent multipe requests until the initial request has finished processing.

Here is the code:

<script type="text/javascript">
var searchValue = $('#Search').val();
$(
function () {
    setTimeout(checkSearchChanged, 0.1);
});

function checkSearchChanged() {
   
var currentValue = $('#Search').val();
   
if ((currentValue) && currentValue != searchValue && currentValue != '') {
        searchValue = $(
'#Search').val();
        $(
'#submit').click();
    }
   
else {
        setTimeout(checkSearchChanged, 0.1);
    }
}

</script>

<
h2>Search</h2>
<% using (Ajax.BeginForm("SearchResults", new AjaxOptions { UpdateTargetId = "searchResults", OnSuccess = "checkSearchChanged" }))
{ %>
    Search: <%
= Html.TextBox("Search", null, new { @class = "wide" })%><input id="submit" type="submit" value="Search" />
<% } %>

<div id="searchResults"></div>

That's it!

 

 

Print | posted on Tuesday, December 21, 2010 11:03 AM | Filed Under [ MVC ]

Feedback

Gravatar

# re: Simple Interactive Search with jQuery and ASP.Net MVC

bad example
5/15/2014 5:09 AM | Prashant
Post A Comment
Title:
Name:
Email:
Comment:
Verification:
 
 

Powered by: