How to Search a Website Using ASP.NET 3.5 - screencast


I'm happy to say that today, we are posting our very first article on ASP.NET. In this screencast, I'll show you how to implement a simple search functionality into your personal website. We'll go over many of the new features in ASP.NET 3.5, such as LINQ and many of the AJAX controls that ship with Visual Studio/Web Developer.

*Click on the full screen icon maximize the video.

Mission Statement

We will be building a simple search functionality for our site. We'll create a bare bones site that contains a single textbox and button. When the button is clicked, we'll write some LINQ code that will retrieve the applicable information from our database and display it on the page. Additionally, we'll allow for partial page post-backs by using the Update Panel and Update Progress controls.

What You Need to Know

In this screencast, I will assume that you have some knowledge of the framework. So, though I will explain everything to the best of my ability, I will expect you to know a few things. If you are a complete novice, leave a comment and we'll work on getting a "From Scratch" article published sometime in the near future.

Step 1: Creating The Database

I'll be creating a "Blog" database. For the sake of simplicity, I'll only add a few columns: "BlogId", "BlogTitle", "BlogContents". In a real world situation, you should add things like "BlogAuthor", "BlogFeaturedImage", "CommentsId", etc. After filling these columns with some gibberish content, we're ready to build our webform.

database image

Step 2: The Listview Control

The wonderful thing about the listview control is that it allows you to maintain 100% control over your mark up. Instead of having to deal with tables, I can specify anything that I like.

  <asp:ListView runat="server" ID="lv">
            <asp:PlaceHolder runat="server" ID="itemPlaceholder" />
        <asp:HyperLink runat="server" ID="link" 
                        Text='<%#Eval("BlogTitle") %>' 
                        NavigateUrl='<%#Eval("BlogId", "entry.aspx?BlogId={0}") %>' /> 
</ItemTemplate> </asp:ListView>
  • LayoutTemplate: This template serves as the wrap for each item. For instance, if each item was inside of an "li" tag, you could add a "ul" tag in your layout template as a "wrap".
  • ItemTemplate: This will describe the layout for each item in the database. If, for example, we have 10 blog entries in the database, there will subsequently be 10 items.

Within the item template, I've specified that the listview control should only display a hyperlink. This hyperlink will have its text attribute equal to whatever the value is in the database for the associated row. I'm also going to set the NavigateUrl property (the href) to a new page. This entry.aspx page will serve to be the template for each entry. We'll specify which entry should be displayed via the querystring. (More on this in the screencast.)

Step 3: LINQ

LINQ is a programming model that allows you to access many different forms of data using the same syntax. With LINQ to SQL, it allows for a strongly typed way of communicating with your relational database. Imagine being able to use the same query to access XML, Objects, Relational Databases, APIs, etc. It's an incredible model and is easily my favorite new feature in ASP.NET 3.5.

Rather than embedding SQL code directly into your code behind files, you can now treat each column in your database tables like any other object. This is accomplished by creating a LINQ to SQL Class. This class automatically creates the database objects for you.

    Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmit.Click

        Dim db As New BlogDBDataContext()

        Dim q = From b In db.Blogs _
                Where b.BlogContents.Contains(txtSearch.Text.Trim()) Or _
                      b.BlogTitle.Contains(txtSearch.Text.Trim()) _
                Select b

        lv.DataSource = q

    End Sub

When the user clicks on the "Search" button, this code will retrieve only the entries from the database that contain the value that was entered into the search textbox. Those values will be returned and stored in the variable "q". We then set the datasource of our listview control to "q" - and databind it.


Step 4: AJAXifying Our Page

In this simple demonstration, it won't truly make a difference whether the entire page posts back or not. However in a mid to large sized site, performing an entire post back can be a pain. We're going to wrap the contents of our listview control within an update panel in order to only refresh this specific information.

  <asp:UpdatePanel runat="server" ID="up">
    <asp:AsyncPostBackTrigger ControlID="btnSubmit" />
        <asp:ListView runat="server" ID="lv">
            <asp:PlaceHolder runat="server" ID="itemPlaceholder" />
        <asp:HyperLink runat="server" ID="link" 
                        Text='<%#Eval("BlogTitle") %>' 
                        NavigateUrl='<%#Eval("BlogId", "entry.aspx?BlogId={0}") %>' /> 
</ItemTemplate> </asp:ListView> </ContentTemplate> </asp:UpdatePanel>

Note the "Triggers" tag. If our button was nested inside of the update panel, the update panel would automatically refresh when the button was clicked. However, in this case, our button is outside of the update panel. In such instances, we need to add an "ASyncPostBackTrigger" that points to the button that will trigger the update panel's post back.

Step 5: User Feedback

Loading Icon
When implementing partial page refreshes, the user can sometimes become perplexed. It may seem to him that the page is simply not responding. To compensate, we'll add the ubiquitous "loading icon" to the page. This will supply the user with some feedback to let him know that the page is in fact processing. We can use the "Update Progress" control to accomplish this task.

<asp:UpdateProgress runat="server" ID="uProgress">
        <img src="img/ajax-loader.gif" alt="Please Wait" />

Within the Progress Template, I've added an image tag that contains my loading icon. So, while the update panel is refreshing, this loading icon will display. When the post back has completed, the icon will disappear.

You're Finished

Though this article moved a bit quickly, the screencast describes every method step by step. If you have any additional questions, please leave a comment and we'll do our best to assist you. What I've supplied today is a simple way to search your site. However, in a real world situation, you'll most likely implement a more advanced search method. I'd love to hear your thoughts on the best ways to accomplish this.

If you'd like more ASP.NET tuts, be heard! Leave a comment and voice your opinion. This framework is too powerful to ignore. Digg it, SU it, DZone it! Thanks everybody! Bye bye!

Subscribe to the Weekly Screencasts

You can add our RSS feed to your ITUNES podcasts by doing the following:

  1. Once ITUNES has loaded, clicked the "Advanced Tab"
  2. Choose "Subscribe to Podcast"
  3. Enter ""

That should do it! The screencast will also be searchable on ITUNES in the next twenty four hours.

Related Posts
  • Code
    Preventing Code InjectionCsrf dotnet retina preview
    Often, websites seem to exist primarily to put something into a database in order to pull it out later. While other database methods, such as NoSQL, have gained popularity in recent years, data for many websites still resides in the traditional SQL database. This data often consists of valuable personal information such as credit card numbers and other personal information of interest to identity thieves and criminals. Hackers therefore always look to get this data. One of the most common targets of these attacks is the SQL databases that lie behind many web applications through a process of SQL Injection.Read More…
  • Code
    iOS SDK
    Working with NSURLSession: Part 3E548b preview image@2x
    In the previous tutorials, we explored the fundamentals of the NSURLSession API. There is one other feature of the NSURLSession API that we haven't look into yet, that is, out-of-process uploads and downloads. In the next two tutorials, I will show you how to create a very simple podcast client that enables background downloads.Read More…
  • Code
    Theme Development
    Creating a WordPress Theme From Static HTML: Adding a LoopCreating wordpress theme from html 400
    In the first three parts of this series, you learned how to prepare static HTML for WordPress and to create a theme by splitting your HTML file into a set of template files and editing the stylesheet. You then uploaded your theme to WordPress and activated it. The theme still isn't displaying any content you add via the WordPress admin however; to do that you need to add a loop to your template files.Read More…
  • Code
    PhoneGap: Build a Feed Reader - Application LogicAudero reader preview2
    This is the second part of the series about Audero Feed Reader. In this article, we'll delve into the business logic of our application and provide additional background on the plugins and API used for our project.Read More…
  • Game Development
    How to Code a Self-Hosted PHP/SQL Leaderboard For Your GamePhp sql self hosted leaderboard 400px
    In this article, we're going to create our first MySQL leaderboard to host on a website or web server using simple PHP and some SQL. We'll then make a simple Unity example in C# using GUIText objects to add new scores to our leaderboard, display the top ten scores and display a user's score and rank.Read More…
  • Code
    JavaScript & AJAX
    Integrating a JS Build Process Into MSBuild in Visual Studio 2012 ExpressMsbuild retina preview
    I've been working with ASP and ASP.NET for about ten years now, starting with ASP classic and settling on .NET 2.0 as my favorite. My new year resolution this year (2013) was to upgrade my .NET work to .NET 4.0 using Visual Studio 2012 Express and really get to grips with MSBuild, so that I can concatenate and minify my JavaScript files as part of the normal build process of a .NET project, in Visual Studio. My first love is to use Ant in NetBeans with a PHP or JSP platform for this kind of work, but my company's main website runs on a .NET platform and it's time to update it, so I decided to bite the bullet and dive back in to some serious study of creating a fully integrated build process using MSBuild. This tutorial will show you how to edit your Visual Studio 2012 Express project file to include your own separate build file which will perform the now widely familiar process of concatenating and minifying a set of JavaScript modules into one file ready for deployment. Read More…