jQuery Search box and Asp.net MVC
This is a simple run through on how to create a fancy search box, that has suggestions underneath the input box, and that also can do autocomplete. For this example I used the Chinook database from codeplex and the Artists table and the autocomplete jquery plug-in that you can find at pengoworks.com.
There are plenty of jQuery plug-ins that do the same thing, I picked this one as it’s very easy to use. As the docs show, the only thing you need to do is hook your input text box up to autocomplete and provide the url where it gets it’s data from. The view looks like this.
<asp:Content ID="headerContent" ContentPlaceHolderID ="headerPlaceHolder" runat ="server"> <script type="text/javascript" src="../../Scripts/jquery.autocomplete.js"></script> <link href="../../Content/jquery.autocomplete.css" rel="stylesheet" type="text/css" /> <script type="text/javascript"> $(document).ready(function() { $("#searchTerm").autocomplete("/Artists/getAjaxResult/"); }); </script> </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> <h2>Look for an artist</h2> <form action="/Artists/Search" method="post" id="searchForm"> <input type="text" name="searchTerm" id="searchTerm" value="" size="10" maxlength ="30" /> <input type ="submit" value="Search" /> </form> <br /> </asp:Content>
As you can see I usually have a container in the header of the master page where javascript and custom css files go. Note that you should use the Url.Content method so you get the proper urls when you deploy this on a ‘real server’.
Now for the backend, we need an action that returns a string of results to the autocomplete call.
public ActionResult getAjaxResult(string q) { string searchResult = string.Empty; var artists = (from a in _db.Artists where a.Name.Contains(q) orderby a.Name select a).Take(10); foreach (Artist a in artists) { searchResult += string.Format("{0}|\r\n", a.Name); } return Content(searchResult); }
By using linq to sql I get the top 10 results from the database from the Artists table and return that as a string to the autocomplete call. The user’s input string is a string called q that is put into the action as a url parameter like this: artists/getAjaxResult/?q=symphony. In order to make that work, you need to add a route to the routes table.
routes.MapRoute( "ArtistSearch", "Artists/Search/{searchTerm}", new { controller = "Artists", action = "Search", searchTerm = "" } ); routes.MapRoute( "ArtistAjaxSearch", "Artists/getAjaxResult/", new { controller = "Artists", action = "getAjaxResult" } );
The first route is used once the user has pressed the submit button, the ArtistAjaxSearch is used for the autocomplete script.
So what happens when the user presses the submit button, whether or not he picked an item from the autocomplete results ?
[AcceptVerbs(HttpVerbs.Post)] public ActionResult Search(string searchTerm) { if (searchTerm == string.Empty) { return View(); } else { // if the search contains only one result return details // otherwise a list var artists = from a in _db.Artists where a.Name.Contains(searchTerm) orderby a.Name select a; if (artists.Count() == 0) { return View("notfound"); } if (artists.Count() > 1) { return View("List", artists); } else { return RedirectToAction("Details", new { id = artists.First().ArtistId }); } } }
As you can see, when a single result is found the details view is shown to the user, by using a redirect to the details method. If there is more than one result, the list of artists is shown. When nothing is found, a simple message is shown. You can of course move the search term to that view as well, to show the user what input he did etc., but that is straightforward stuff.
Another way to do this, would be to insert the artist table as an array and let the autocomplete script use those values for it’s magic, all on the client side. This would be doable as long as that table wouldn’t get too long. If there are 1000s of records, this wouldn’t be a very good solution
.
Hope this helps someone out there
, feel free to add any comments or questions !
Trackbacks
- 9eFish
- ASP.NET MVC Links :: eric.ness.net
- Interesting Finds: 2009-04-20 - Bolik
- 10+ JavaScript & jQuery MVC Tutorials | jQuery4u
- Share 16 of the MVC tutorial javascript & jQuery - Open News
Comments are closed.
Great Post! One thing I would be cautious on is in the Search Action Method assuming that if one artist is returned from the query that is the correct artist. I would think from a user experience factor that doing a search that only returns one result would still show the search listing with just the one result posted. The user can then decide to click through to the details page or search again…
Thanks
.
Yes I think that’s a matter of personal preference. When I search and I get a list of just one item, I always wonder why not just show me the details of the one thing
.
Chances are you will want string ToLower() the a.Name call if you want case invariant matching.
Thanks for the article!
thanks
Cool post! One thing you might want to do is use a StringBuilder instead of concatenating your strings in getAjaxResult(…).
Ah yeah, thanks for the suggestion
.
good example, thx
It dioesnt work for me
Tnx for this fancy searchbox only the autocomplete doesn’t work
It’s one of the many options you can use with the autocomplete script, where you want autocomplete or not. So maybe you just need to turn it on !
I’m interested in using this same functionality on a site I’m developing. However, the site is coded in VB. Can you provide the VB equivalent of the C# presented in your post?
No I am afraid not. I am not a MS employee of some sort, you’ll have to figure that out on your own.
It seems nice solution please can you send me source code of this sapmle project
Good Example ,thanks ………..
sohbet, chat, mirc, muhabbet, adatr, sanal sohbet
Crap, didn’t realise that would happen
If I remove the li tags then the link works.
thats good
Could you please provide an example for using autocomplete in editing the jqgrid.
M stuck there. Searched everything but no clues. My autocomplete just does not work.
Thanks,
Bhoomi.
x0yZET http://dhY3n0fjvTtj48mG9sFnCv.com
NsvaQN http://fnYwlOpd2n9t4Vx6A3lbk.com
Thank you , it was very useful for a beginner like me….it worked like a treat…
Have you got any ? Kds Sex 8DD
dfgdsgdf
I’d like to cancel a cheque Preteen Nudes
97281