Have you ever been to a website to look for something, but you have no idea where to look, and you wished they had a search bar? Well, adding a search bar in ASP is easy enough with Bing. Sign up for an application ID and build the request and response handlers. Let’s look at the basics of setting up Bing for your site and follow up with a few examples.
There are two great articles on how to setup Bing, the first I found on ASP’s community page, which shows how to add Bing to a MVC 3 site, and the second shows how to add Bing using jQuery. The only difference between the two is how the request and response are handled. Now, let’s look at the process as a whole and view condensed examples from those articles just mentioned.
The Basics 1. A Bing App ID – can be retrieved at Bing’s Developer Center (requires Live ID).
2. Basic Knowledge of Bing’s API – documentation can be found on MSDN, but basically all you need to know is the query request URL:
3. Handle the Request and Response – Now for our two examples,
ASP:
code:
Dim appid, siteURL, query appid = "###"; siteURL = "http://yoursite.com"; query = "search for this"; var url = string.Format("http://api.search.live.net/json.aspx?Appid={0}&sources=web&query=site:{1} {2}", appid, siteURL, query); var result = string.Empty; var webRequest = WebRequest.Create(url); webRequest.Timeout = 2000; using (var response = webRequest.GetResponse() as HttpWebResponse) { if (response.StatusCode == HttpStatusCode.OK) { var receiveStream = response.GetResponseStream(); if (receiveStream != null) { var stream = new StreamReader(receiveStream); result = stream.ReadToEnd(); } } } if (!string.IsNullOrEmpty(result)) { var javaScriptSerializer = new JavaScriptSerializer(); var apiResponse = javaScriptSerializer.Deserialize(result); result = apiResponse.SearchResponse; }jQuery:
// assumes there is a button with id 'search' and a text input with id 'query' var appid = '###'; var siteURL = 'http://yoursite.com'; $('#search').click(function (event) { var query = encodeURIComponent($("#query").val()); var url = 'http://api.search.live.net/json.aspx?Appid=' + appid + '&query=' + query + '&sources=web'; $.getJSON(url, function (data) { var results = data.SearchResponse.Web.Results; }); });
There’s more than one way to accomplish this task, but these two examples give a taste of just how easy it is to add search functionality on your site. Allowing viewers to search your site is a great opportunity for creating media buzz to attract new visitors, and keep current ones excited about your service. Feel free to comment with other ways you’ve accomplished site searching on your page.