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...

Comments (11)

Kevin

2/3/2011 7:40:45 PM
Thanks for this write up. Playing around with it today. Shouldn't the search results render properly inside a DIV, so that I can put a brief Contact us Form next to them?

Jason Skowronek

2/3/2011 8:02:13 PM
The results will render to the (in my example) <div id="cse" /> container. So It shouldn't affect any other elements on the page directly.

Josh

2/14/2011 5:05:05 PM
Hi- Thanks so much for this. It's a real help. I'm having issues with the search results page. It doesn't want to compile. I'm a bit new to ASP, so I must be doing something wrong...I'm confused with the javascript you provided versus what I should include from Google...what did you modify/what should I leave alone? Thanks again- -Josh

Josh

2/16/2011 3:55:46 PM
I'm still having issues with this - I'm guessing the problems are arising from the search results page's script...should I be substituting div id's for FILTERED_CSE_RESULTSET and LINK_TARGET_TOP?

Jason Skowronek

2/16/2011 6:28:17 PM
Josh, Sorry you're having troubles with my example. I'll spend some more time and update it so that my example snippets, when combined, will function as stated. Look for it in the next couple of days. If you want, send me your code via my contact form and I'll see if I can quickly get you on the right track. Take care.

rebecca

5/2/2011 7:13:20 PM
hi i want to use my own textbox instead of google's textbox? how can i do that?

Jason Skowronek

5/2/2011 8:26:52 PM
Rebecca, Other than programming your own search form and then hitting the search API's yourself, the only way to change the layout is using the style selectors for the id's and classes that the CSE JavaScript library renders. gsc-input and gsc-search-button are the two directly related to CSE rendered control.

Phil Donnell

8/4/2011 8:57:42 PM
Thank you! Excellent example. Saved me hours of time.

Jason Skowronek

8/4/2011 9:08:59 PM
You're welcome. Thanks for feedback!

Nour

5/13/2012 6:33:40 PM
i didnt understand what does this code mean:rel="{0}?q={1}"

Jason

5/16/2012 4:53:27 AM
The content in the rel attribute is strictly a string format used in the redirect method. If you look through the function you can see the attribute["rel"] being referenced and then formatted.
Leave a comment
Name *
Email *
Homepage
Comment

Recommend

Nero Sale 150x150 

System Mechanic 

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