This second post is aimed at building the search box that will be used for sending the query to the page containing the search results. Normally this would be an easy task of just creating a form and setting the action url to your results page. Due to the way we are creating cleaner URL’s, it isn’t quite as straightforward.
The Form Tag
The first thing that you need to make sure of is that the search input box we are going to create is contained within a form tag. Now you can either wrap the input field in a form, or, like I do, put the whole page content inside a form. The way I do it is by adding the following immediately after my opening body tag and close it just before my closing body tag in my master page:
<form id="form" runat="server">
This way you can handle multiple HTML controls if you happen to have more than on on your page.
The Search Box
For my search box I have built all of the functionality into a single Razor script. My script looks like the following (you will also need an accompanying Macro if you copy and paste):
@if (IsPost && !string.IsNullOrEmpty(Request["query"]) && !Request["query"].Equals("Search..."))
{
Response.Redirect("/search/" + Request["query"] + "/1/");
}
<div class="widget">
<div class="widget-inner">
<h4>Search</h4>
<input type="text" name="query" id="query" value="Search..." onfocus="if (this.value == 'Search...') {this.value = '';}" onblur="if (this.value == '') {this.value = 'Search...';}" />
</div>
</div>
Now, as you can see there are two parts to this script. The first part is a small piece of Razor which checks if the page is a postback, if there was a query in the search box and that it wasn’t the default text, “Search…”. As long as it wasn’t any of these things, the search is redirected to one of our nice URL’s we set up in the first part of this tutorial.
The HTML below the redirection code is what I use to create my search form on the page. When the user presses enter, due to the input being inside the form tag we created at the beginning of this post, the page is posted back to itself (thus, the postback check in the code) which in turn causes the redirection to the search page.
Putting it on a Page
Now that you have created the Macro and related Razor script, you are ready to put it onto your site. This is as simple as finding where in your template you would like to display it and inserting the Macro using the “Insert Macro” menu item.