Dela via


Walkthrough: Creating an Ajax-Enabled Data Application

This walkthrough describes how to create an AJAX-enabled Web application that can work as a to-do or task list. It helps you create a basic user interface for creating, managing, and deleting lists, and for the items in those lists. All the insert, update, delete, sort, and paging operations are performed inside an UpdatePanel control that uses Microsoft Ajax.

You can use the UpdatePanel control to enable asynchronous postbacks on a page. By default, ASP.NET refreshes the whole page when a postback occurs. However, when you use the UpdatePanel control to create asynchronous postbacks, only the page elements that are inside the UpdatePanel control are changed. This makes the page feel more dynamic and perform faster, and it provides a richer user experience.

Tasks illustrated in this walkthrough include the following:

  • Creating a SQL database and adding data.

  • Adding a LinqDataSource control to a page.

  • Adding a LINQ to SQL Classes file.

  • Using the ListView control to display, edit, and delete data.

  • Using the LinqDataSource control to connect to a database by using Language-Integrated Query (LINQ). For more information, see LINQ (Language-Integrated Query).

  • Using the UpdatePanel control to add AJAX functionality to the page.

Prerequisites

To complete the walkthrough, you will need the following:

  • Microsoft Visual Studio or Visual Web Developer 2010 Express. For download information, see the Visual Studio Development Center Web site.

  • SQL Server Express installed on your computer. If you have SQL Server installed, you can use that instead, but you must make small adjustments to some of the procedures.

Creating a Web Site

In this part of the walkthrough, you create a Web site and add a page to it. In the next section, you connect to a database. If you have already created a Web site (for example, by following the steps in Walkthrough: Creating a Basic Web Page in Visual Studio), you can use that Web site for this walkthrough. Otherwise, create a new Web site by following these steps.

This walkthrough uses a Web site project. You could use a Web application project instead. For information about the difference between these Web project types, see Web Application Projects versus Web Site Projects.

To create a new file system Web site

  1. In Visual Web Developer, in the File menu, click New Web Site.

    The New Web Site dialog box is displayed.

  2. Under Visual Studio installed templates, click ASP.NET Web Site.

  3. In the Location box, click File System and type the name of the folder in which you want to keep the pages of the Web site.

  4. In the Language list, click Visual Basic or Visual C#, and then click OK.

    Note

    The programming language that you select will be the default for the Web site, but you can set the programming language for each page individually.

    Visual Web Developer creates the folder and a new page named Default.aspx.

Creating a New SQL Server Database

Now that you have a Web site, the next step is to create a database and add a reference to the database in Server Explorer. (In Visual Web Developer 2008 Express Edition, Server Explorer is named Database Explorer.) When you add a database to Server Explorer, you can use Visual Studio to add tables, stored procedures, views, and so on. You can also view table data or create your own queries by hand or graphically by using the Query Builder window.

To add a database to the project

  1. In Solution Explorer, right-click the Web site name and then click Add New Item.

    The Add New Item dialog box is displayed.

  2. Select SQL Database, name the database Tasks.mdf, and then click OK.

  3. When Visual Studio asks whether the database should be stored in the App_Data folder, click Yes.

Creating a Schema and Sample Data for the Database

You can use the database design and editing features to create a schema for the new table that stores the task items.

To create a schema and sample data for the database

  1. In Solution Explorer, open the App_Data folder and double-click Tasks.mdf.

    The Tasks database tree hierarchy is displayed in Server Explorer (or Database Explorer).

  2. Right-click the Tables folder and then click Add New Table.

  3. In the database table editor, create the following columns in the table:

    Column Name

    Data Type

    Properties

    taskId

    int

    Allow Nulls: No

    taskName

    nvarchar(50)

    Allow Nulls: No

    dateCreated

    datetime

    Allow Nulls: No

    isComplete

    bit

    Allow Nulls: No

  4. Right-click the row that contains taskid and then click Set Primary Key.

  5. With the taskid row still selected, in the Column Properties tab, open the Identity Specification section and then set (Is Identity) to Yes.

  6. Save the table and name it TasksList.

  7. Right-click the table in Server Explorer and click Show Table Data.

    A window is displayed where you can view and add data.

  8. Add four or five records to the table, and then close the database designer.

    You do not have to specify a value for taskid, because it is an identity column whose value is automatically assigned. You must specify either False or True for the isComplete field.

Creating the Data Access Controls

In this section, you will use the LinqDataSource control and create classes that represent database entities. The control and the classes that are created are the data-access layer that will be used in this walkthrough.

The LinqDataSource control exposes Language Integrated Query (LINQ) to Web developers through the ASP.NET data-source control architecture. The LinqDataSource control creates the code for selecting, inserting, updating, and deleting objects in the database. LINQ applies the principles of object-oriented programming to relational data. It provides a unified programming model for querying and updating data from different kinds of data sources and extends data capabilities directly into the C# and Visual Basic languages. For more information about LINQ, see LINQ (Language-Integrated Query).

Mapping the Tasks Database to a SQL Data Context Object

To begin creating the data access layer, you add a typed dataset to the project.

To create a class for the TasksList table

  1. If the Web site does not already have an App_Code folder, in Solution Explorer, right-click the Web site name, click Add ASP.NET Folder, and then click App_Code.

  2. Right-click the App_Code folder and then click Add New Item.

  3. Under Visual Studio installed templates, select LINQ to SQL Classes, rename the file to Tasks.dbml, and then click Add.

    The Object Relational Designer is displayed.

  4. In Server Explorer, drag the TasksList table into the Object Relational Designer window.

  5. Save the Tasks.dbml file.

    When you save the file, Visual Studio creates two files in the App_Code folder under Tasks.dbml. The first file is Tasks.dbml.layout. The second file is Tasks.designer.cs or Tasks.designer.vb, depending on the language that you selected when you created the Tasks.dbml file.

  6. In Solution Explorer, open the Tasks.designer.cs or Tasks.designer.vb file.

    Notice that the code contains classes named TasksDataContext and TasksList. The TasksDataContext class represents the database, and the TasksList class represents the database table. The parameterless constructor for the TasksDataContext class reads the connection string from the Web.config file.

  7. Open the Web.config file.

    Notice that a connection string to the Tasks.mdf database has been added in the connectionStrings element.

  8. Close the class file, the Object Relational Designer window, and the Web.config file.

Creating and Configuring a LinqDataSource Control

Now that you have a database table and classes that represent database entities, you can use a LinqDataSource control on an ASP.NET Web page to access the database.

To create and configure a LinqDataSource control

  1. Open or switch to the Default.aspx page.

  2. Switch to Design view.

  3. Drag a LinqDataSource control onto the page.

    You can leave the ID property as LinqDataSource1.

  4. In the LinqDataSource Tasks smart tag panel, click Configure Data Source.

    Note

    If the smart tag panel is not displayed, right-click the LinqDataSource control and then click Show Smart Tag.

  5. In the Choose your context object list, select TasksDataContext, and then click Next.

  6. In the Table list, select TasksLists(Table<TasksList>), and then click Finish.

  7. From the LinqDataSource Tasks menu, select Enable Delete, Enable Insert, and Enable Update.

    Notice that you did not have to specify any database commands for selecting the data.

  8. Save the page.

Using the Data Source Controls

In this section, you will add controls to the page that use the LINQ to SQL Classes file that mapped the database table to classes. You will also use the LinqDataSource control to create a basic data application.

You will add a ListView control to display data from a SQL Server database. You will then add a DropDownList control to filter the data that appears in the ListView control. Later in the walkthrough you will put the controls into an UpdatePanel control to add asynchronous postback capabilities.

Displaying Data with a ListView Control

The ListView control is useful for displaying data in any repeating structure, similar to the DataList and Repeater controls. However, unlike those controls, the ListView control supports edit, insert, and delete operations as well as sorting and paging.

You will add a ListView control that shows all the tasks. Later, you will add a drop-down list that lets you filter the data. The ListView control formats the presentation of the data and displays buttons that can be used to edit and update the content, or to insert new content.

To add a ListView control to the page

  1. Open or switch to the page where you added the LinqDataSource control.

  2. From the Data tab of the Toolbar, drag a ListView control onto the page.

  3. In the ListView Tasks menu, in the Choose Data Source list, select LinqDataSource1.

    This binds the ListView to the LinqDataSource control that you configured earlier in the walkthrough.

  4. In the ListView Tasks smart tag panel, click Configure ListView.

  5. In the Configure ListView dialog box, select Enable Editing, Enable Inserting, Enable Deleting, and Enable Paging.

  6. Click OK.

  7. Save the page.

Adding a DropDownList Control to Filter Data

You can filter the data that is displayed in the ListView control by creating a drop-down list that lets you select which tasks to show. For this example, you will create a list that displays either tasks that are active or tasks that have been completed.

You can put code in the ListView control to auto-generate a Where clause to display only the records that match the selection in the DropDownList control.

To add a control to filter data

  1. Open or switch to the Default.aspx page and switch to Source view.

  2. Inside the form element and above the ListView control, add the following markup:

    <span id="filter">
      Current List Filter: 
      <asp:DropDownList ID="DropDownList1" 
        AutoPostBack="true" 
        runat="server">
      <asp:ListItem Text="Active" Value="False" />
      <asp:ListItem Text="Completed" Value="True" />
      </asp:DropDownList>
    </span>
    <hr id="separator" />
    
  3. In the LinqDataSource control, set the AutoGenerateWhereClause property to true, as shown in the following example:

    <asp:LinqDataSource ID="LinqDataSource1" runat="server" 
      ContextTypeName="TasksDataContext" 
      TableName="TasksLists" 
      EnableDelete="True" 
      EnableInsert="True" 
      EnableUpdate="True" 
      AutoGenerateWhereClause="true" >
    
  4. Add the following markup for Where parameters between the opening and closing tags of the LinqDataSource control.

    <WhereParameters>
      <asp:ControlParameter 
        Name="isComplete" 
        ControlID="DropDownList1" 
        Type="Boolean" />
    </WhereParameters>
    
  5. Save the page.

You can now test the page to make sure that it displays the data that you select.

To test the page

  1. Press CTRL+F5 to display the page in the browser.

  2. Select Completed from the drop-down list.

    If you have tasks that are marked as complete, you see only those tasks.

Adding AJAX Functionality to the Page

In this section you will add a ScriptManager control to the page to enable the AJAX features of ASP.NET. You will then add an UpdatePanel control to the page, which lets you perform tasks in the ListView control without a full page postback.

Adding a ScriptManager Control

To use any ASP.NET AJAX features such as the UpdatePanel control, you must add a ScriptManager control to the page.

To add a ScriptManager control to the page

  1. Open or switch to the Default.aspx page and switch to Source view.

  2. In the AJAX Extensions tab of the toolbox, double-click the ScriptManager control to add it to the page inside the form element.

Putting the ListView Control in an UpdatePanel Control

For this example, you will put the ListView inside an UpdatePanel control. Changes to the ListView control will not require a full postback.

To put the ListView control inside an UpdatePanel control

  1. In the Default.aspx page, add the following markup directly after the opening <form> tag:

    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>
    
  2. Add the following code directly before the closing </form> tag:

    </ContentTemplate>
    </asp:UpdatePanel>
    

    This code puts an UpdatePanel control around the ListView control and the DropDownList control.

  3. Save the page.

You can now test the page again.

To test the page

  • Press CTRL+F5 to view the page in a browser.

    Notice that when you select Active or Completed from the list filter, a full postback does not occur and the ListView displays the updated list of data without a flicker.

Next Steps

This walkthrough showed you how to add a ListView to a page with a LinqDataSource control to add, modify, and delete tasks from a database. You then added AJAX functionality by using the UpdatePanel control.

You can find more information about how to work with databases in walkthroughs such as Walkthrough: Data Binding to a Custom Business Object and Walkthrough: Creating Master/Detail Web Pages in Visual Studio.

See Also

Concepts

LinqDataSource Web Server Control Overview

Microsoft Ajax Overview

Partial-Page Rendering Overview