Advertisement
ASP.NET

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

by

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">
        
        <LayoutTemplate>
            <asp:PlaceHolder runat="server" ID="itemPlaceholder" />
        </LayoutTemplate>
        
        <ItemTemplate>
        <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.

LINQ
    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
        lv.DataBind()

    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.

UI

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">
    <Triggers>
    <asp:AsyncPostBackTrigger ControlID="btnSubmit" />
    </Triggers>
        <ContentTemplate>
        
        <asp:ListView runat="server" ID="lv">
        
        <LayoutTemplate>
            <asp:PlaceHolder runat="server" ID="itemPlaceholder" />
        </LayoutTemplate>
        
        <ItemTemplate>
        <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">
    <ProgressTemplate>
        <img src="img/ajax-loader.gif" alt="Please Wait" />
    </ProgressTemplate>
</asp:UpdateProgress>

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 "http://feeds.feedburner.com/NETTUTSVideos"

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

Related Posts
  • Code
    ASP.NET
    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
    PhoneGap
    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
    Implementation
    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
    Scala
    Building Ribbit in ScalaRibbit scala retina preview
    In this tutorial we will implement the Ribbit application in Scala. We'll be covering how to install the Play web framework, a NetBeans plugin for it, and finally the code in Scala. If you are new to Scala, check out this previous tutorial which will help you set up your environment and provides you with a general platform that you can build upon. Even though the essence of Ribbit is to create/send/read Ribbits (our version of tweets), we will spend a large part of this tutorial explaining how Play works, authentication, and persistence. After these are in place, the rest becomes much easier. We will also implement ribbit creation, submission and listing out all ribbits. Following someone, advanced user settings, and direct messages will be an extra assignment for you to complete on your own. I am sure if you manage to follow along with this tutorial and create Ribbit as explained below, these three functionalities will be easily accomplished as homework.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…