Home → Resources → Articles

How To Implement a Google Custom Search Engine on an ASP.NET Based Website

(Microsoft .NET,Microsoft ASP.NET,Web Programming,HTML,CSS,JavaScript) by Jason Skowronek on 01/20/2011

Updated: February 16, 2011 

This article demonstrates a basic implementation of a Google Custom Search Engine (CSE) on an ASP.NET based website.

Create and Configure a Custom Search Engine

Log in and create a custom search engine account. Standard edition is free, but requires that you display the ads on the results pages. Site Search is the paid edition, starts at $100 / month, and is ad-free.

While following the create wizard, customize your search engine. Customizing the Minimalist style makes it easy to style your results page by leveraging the rendered CSS to include into your own stylesheets.

Once the search engine has been created, the create wizard will generate the HTML output needed to drop on the webpages.

Here is an example JavaScript block:

<div id="cse" style="width: 100%;">Loading</div>
<script src="http://www.google.com/jsapi" type="text/javascript"></script>
<script type="text/javascript">
  google.load('search', '1', {language : 'en', style : google.loader.themes.MINIMALIST});
  google.setOnLoadCallback(function() {
    var customSearchControl = new google.search.CustomSearchControl('%YOUR CSE KEY WILL BE HERE%');
    customSearchControl.setResultSetSize(google.search.Search.FILTERED_CSE_RESULTSET);
    customSearchControl.draw('cse');
  }, true);
</script>

Search Input Form

Drop a <asp:textbox /> and <asp:linkbutton /> control either on your Default.master or another .aspx page to handle the global search input elements.

<asp:textbox id="Textbox1" runat="server" rel="/Search.aspx?q={0}" />
<asp:linkbutton id="LinkButton1" runat="server" Text="Search" onclick="LinkButton1_Click" />

There are many ways to handle triggering the search request. In this example, a keypress handler is bound to the keypress even of the textbox using jQuery.

$(document).ready(
	function ()
	{
		$('#<%= Textbox1.ClientID %>').bind('keydown', function (e)
		{
			if (e.which == 13)
			{
				// trigger the __postBack() event of the linkbutton
				window.location = $('#<%= LinkButton1.ClientID %>').attr('href');
				return false; // don't capture any keypress event
			}
		});
	});

Handle the linkbutton click event. (This should be done in the code behind or business classes) 

protected void LinkButton1_Click(object s, EventArgs e)
{
	// use the relationship (rel) attribute of the
	// textbox to store the url formatter string
	string searchURL = String.Format(Textbox1.Attributes["rel"],
	HttpUtility.UrlEncodeUnicode(Textbox1.Text));
	Response.Redirect(searchURL, true);
}

Search Results Page

On the Search.aspx page, drop the HTML code provided by the Google CSE creation wizard. The code below has been modified to handle the rendering events of the CSE in order to synchronize the site search textbox with the search queries entered into the CSE.

google.load('search', '1', { language: 'en' });
google.setOnLoadCallback(function ()
{
	var customSearchControl = new google.search.CustomSearchControl('%GOOGLE_CSE_KEY%');
	customSearchControl.setResultSetSize(google.search.Search.FILTERED_CSE_RESULTSET);
	customSearchControl.setLinkTarget(google.search.Search.LINK_TARGET_TOP); // target the parent iframe
	customSearchControl.setSearchCompleteCallback(window, onSearchComplete, this); // handle callback
	customSearchControl.draw('cse');
	customSearchControl.execute('<%= HttpUtility.HtmlEncode(Request.QueryString["q"]) %>');
}, true);

function onSearchComplete(search)
{
	$('#<%= Textbox1.ClientID %>').val(search.Tc);
}

Your search page then just needs the CSE DIV to which the search form and results will be rendered.

<form runat="server">
	<div id="cse" style="width: 100%;">Loading</div>
</form>

Here is the entire page in a working example. Here is a working example of the Google Customer Search Engine.

<%@ page language="C#" autoeventwireup="true" %>
<script language="c#" runat="server">
	protected void Search_Click(object s, EventArgs e)
	{
		// use the relationship (rel) attribute of the
		// textbox to store the url formatter string
		string searchURL = String.Format(SearchBox.Attributes["rel"], Request.Url.AbsolutePath, HttpUtility.UrlEncodeUnicode(SearchBox.Text));
		Response.Redirect(searchURL, true);
	}
</script>
<!doctype html>
<html>
	<head runat="server">
		<title>Google Search Example</title>
		<script type="text/javascript" src="//www.google.com/jsapi"></script>
		<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
		<script type="text/javascript">
			$().ready(function ()
			{
				$('#<%= SearchBox.ClientID %>').bind('keydown', function (e)
				{
					if (e.which == 13)
					{
						// trigger the __postBack() event of the linkbutton
						window.location = $('#<%= Search.ClientID %>').attr('href');
						return false; // don't capture the keypress event
					}
				});
			});

			google.load('search', '1', { language: 'en' });
			google.setOnLoadCallback(function ()
			{
				var customSearchControl = new google.search.CustomSearchControl('002003371182621917485:m90nacd99nk');
				customSearchControl.setResultSetSize(google.search.Search.FILTERED_CSE_RESULTSET);
				customSearchControl.setLinkTarget(google.search.Search.LINK_TARGET_TOP); // target the parent iframe
				customSearchControl.setSearchCompleteCallback(window, onSearchComplete, this);
				customSearchControl.draw('cse');
				customSearchControl.execute('<%= HttpUtility.HtmlEncode(Request.QueryString["q"]) %>');
			}, true);

			function onSearchComplete(search)
			{
				$('#<%= SearchBox.ClientID %>').val(search.Ic);
			}
		</script>
	</head>
	<body>
		<form runat="server">
			<asp:textbox id="SearchBox" runat="server" rel="{0}?q={1}"  />
			<asp:linkbutton id="Search" runat="server" text="Search" onclick="Search_Click" />
			<div id="cse" style="width: 100%;">Loading...</div>
		</form>
	</body>
</html>


Conclusion

Implementing a Google Custom Search Engine is fairly straight forward with the results being quite impressive. The Google Custom Search Engine API's are equally robust if you have the bandwidth to dig into the framework as well.

Carry on...

 

Recommend

UltraEdit

Nero Sale 150x150 

CS5 Web Premium - Download 

SkoNet provides comprehensive digital consulting services such as: web development, applications development, database design and architecture, business process management, customer relationship management, and many others that help businesses of every size, industry, and geography meet the complex challenge of managing and sharing information on the web. Our skills and expertise in online systems allow us to help customers build applications ranging from simple, single-page web sites to robust enterprise systems.

Online Backup, Ektron Consulting, Ektron Programmer, Ektron Developer, Ektron Partner Utah, Ektron Partner, Ektron Architect, Ektron Hosting, Salesforce.com Consultant Utah, Salesforce.com Partner Utah, Salesforce.com Partner, Salesforce.com Programmer, Salesforce.com Architect, Salesforce.com APEX Programmer