Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Beginning ASP.NET 2

.0.pdf
Скачиваний:
23
Добавлен:
17.08.2013
Размер:
24.67 Mб
Скачать

Reading Data

5.Now add the other two games in the same manner and save the file. The additional games will be as follows. (For the sake of completeness, the first game is included again.)

<Games>

<Game Number=”1”> <Date>2007/10/21</Date> <Home>WroxUnited</Home> <Visitor>Clatterham</Visitor>

</Game>

<Game Number=”2”> <Date>2007/10/22</Date> <Home>Mellingham </Home> <Visitor>WroxUnited</Visitor>

</Game>

<Game Number=”3”> <Date>2007/10/22</Date> <Home>WroxUnited</Home> <Visitor>Fulchester</Visitor>

</Game>

</Games>

6.If you run the file the XML data will be sent to the browser, and most browsers can render a simple presentation (see Figure 7-44). Try it, noting that there is no ASP.NET 2.0 involvement yet.

Figure 7-44

259

Chapter 7

How It Works

You saw in this exercise that you start with a top-level node named <Games>. Then, being careful not to make typos in the case, you added a node for the first game. The data for that game was organized in two ways. The number of the game was placed in the <Game> tag as an attribute. But you chose to place the date and competitors in separate tags at a lower level than the <Game> tag. After running the file you saw how your browser handles a raw XML file. In the next section you see what ASP.NET 2.0 can do with that information.

Reading XML Data

Because XML data is organized as a hierarchy, ASP.NET 2.0 provides alternate data source and databound controls from those you used with tabular data earlier in the chapter. The XML data source control provides the data source control for most cases. The key property that must be set in this control is the name of the XML database file.

ASP.NET 2.0 supports rendering of tree data with three data-bound controls named TreeView, Menu, and SiteMapPath. The TreeView is a little tricky to set up, as you will see, but then does its job just fine. The TreeView control is fine for any XML data. The Menu control is designed only for its named purpose. The SiteMapPath control renders differently depending on the page that is currently opened. Chapter 2 presented more on this navigation control.

VWD offers a handy way to identify which pieces of data should appear in its rendering. The tool is called the TreeViewDataBindings Editor and it can be opened from the TreeView control’s smart task panel as you will practice in the following exercise.

In the following Try It Out you create a display of the games scheduled for 2007 at the bottom of the

Fixtures.aspx page.

Try It Out

Reading XML Data

1.Open Fixtures.aspx in Design View and drag a TreeView control (in the navigation section of the Toolbox, shown in Figure 7-45) to the bottom of the page.

Figure 7-45

2.On the smart task panel select Choose Data Source and select New. Note that this time you have different choices for a data source; you want to use an XML file (see Figure 7-46).

260

Reading Data

Figure 7-46

3.Specify an ID of Schedule2007XML and then browse to the Schedules2007.XML file that you created. For now, leave the Transform and XPath boxes in the wizard blank. Run the page in your browser (see Figure 7-47) and look at the tree at the bottom of the page:

Figure 7-47

The page is rendering the names of the nodes but not the data of the nodes. Close the browser.

4.In Design View, select the TreeView control, open its smart task panel, and click “Edit TreeNode Data bindings.” Select Game in the top left (the singular Game, not the plural Games) and click Add (see Figure 7-48).

261

Chapter 7

Figure 7-48

5.In the Properties window set the TextField to Number. Staying in the DataBindings editor, select Home, click Add, and set its TextField to #InnerText because you want to display the text between the <Home> and </Home> tags on the page. Repeat for the Date and Visitor data.

How It Works

In the first step you found the TreeView control in the Navigation panel of the Toolbox. After dragging it to the page you can set its source of data the same way that you do for other data-bound controls, by using the Choose Data Source in the smart task panel. But in the case of a TreeView you want to use a hierarchical source, so you pick the XML file you made in the last exercise.

As you observed in the first run of the page, by default you only get the generic names of the nodes, not the actual data. The data is specified by using the TreeViewDataBindings Editor. You can add (or remove) tags to which you want data rendered. Once a field is added you go to the right side and select its TextField property. If you have data within a tag, such as Number within the <Game> tag, then the name of that data will show up without a number sign. If the data is between an opening and closing tag, such as <Home>WroxUnited</Home>, the TextField option will be set to #InnerText.

Binding Syntax

In this book you have taken advantage of VWD’s features to build code and thus spent little time examining the code that was built for you. But it is worth understanding code that actually brings together the data source controls and the data-bound controls. Within a template for a GridView, DataList,

Repeater, DetailsView, or FormView you see the following code:

262

Reading Data

<asp:DataList ID=”DataList1” runat=”server” DataSourceID=”SqlDataSource1”

<ItemTemplate>

<asp:Label ID=”FixtureIDLabel” runat=”server”

Text=’<%# Eval(“FixtureID”) %>’

BackColor=”Yellow”></asp:Label>

</ItemTemplate>

</asp:DataList>

The shaded line instructs the page to bind the Text property of the control named FixtureIDLabel to the field named FixtureID in the data source SqlDataSource1. This method (request for a specific behavior) named Eval() actually performs the connection between one field in the data source control and a rendering mechanism in the data-bound control. Two similar methods exist: Eval() is for readonly, and Bind() allows both read and write (and is covered in the Chapter 8). Within templates VWD will write code to specifically employ these methods. But if there is no templating, the binding is implied and will not appear in the code.

Summar y

ASP.NET 2.0 greatly eases the use of data on a web page by encapsulating most of the code into easy-to- use controls. In this chapter you learned that data source controls and data-bound controls work together. The former provides a connection to an information source, and the latter renders that information onto a page. ASP.NET 2.0 ships with four data source controls (SqlDataSource, AccessDataSource, XMLDataSource, and SiteMapDataSource), each optimized to work with a particular type of data.

This chapter focused primarily on the SqlDataSource control, because it can be used with any database that can understand SQL statements. A fifth data source control, ObjectDataSource, is used for customdesigned business objects.

After learning the basics of data source and data-bound controls, the chapter drilled down into the specifics of how to use them on your pages, specifically covering the following topics:

How to use the GridView, DataList, and Repeater controls to display tabular data.

How to use the DetailsView and FormView controls to display single records.

How to use the ListBox and DropDownList controls to display a selection of records.

How to use the TreeView, SiteMapPath, and Menu controls to display tree data.

Additionally, this chapter covered the use of templates and wizards when setting up data source and data-bound controls. Recall that a template is a space into which you can drag various fields or other controls. Once in a template, these controls can be bound to the record currently shown by the template.

Most data-bound controls offer templates. These spaces can hold many kinds of controls that can be data-bound, including labels, text boxes, and images. All of the bound controls within a template will have their information revised when the user moves from record to record. To change a template you select the control and switch to Template Editing mode. After making your changes, be sure to click the smart task panel’s End Template Editing to revert to normal mode.

263

Chapter 7

Data-bound controls can be configured to display only a portion of the records. This behavior can be set statically by a value in a WHERE clause of the SELECT command of the data source control. The restriction of records can also be set dynamically. The parameter can come from a querystring or another databound control. For example, the selection in a DropDownList (master control) can be used as the parameter of a WHERE clause that limits the records shown in a GridView (child control).

Reading and displaying data is half of the data story. The other half is getting information to flow in the opposite direction. Chapter 8 looks at how to get information from users and write it to your data store.

Exercises

1.Describe the general capabilities of data source and data-bound controls.

2.Which data-bound controls render data in tables?

3.Compare and contrast the DetailsView and FormView controls.

4.Describe how a GridView control can limit its records to only those that match a player’s name selected in a DropDownList of last names.

5.Which data source control is best suited for the Menu or SiteMapPath data-bound controls?

264

8

Writing Data

In Chapter 7 you learned how to read data from a database and present it on a page. In this chapter you study the reverse, how to gather data from a user and write it to a database. When we refer to writing we mean three kinds of operations: the creation of new records, changing existing records, and deleting records. The pattern is the same for all three and the setup is made quite easy with the internal functionality of the data source and data-bound controls, as well as the auto-typing features of VWD. As a bonus this chapter discusses transferring files from the browser to the server and then wraps up with an exercise that integrates several techniques from Chapters 6 through this one.

Introduction to Writing Data

Recall from Chapter 7 that ASP.NET 2.0 uses two groups of controls to work with data. Data source controls provide a connection to a source of data and enable certain behaviors, such as reading and writing to the data source. Data-bound controls provide a user interface on the page that can take advantage of the data source control capabilities. For the most part, the controls are mix-and-match. A DropDownList can use a SqlDataSource, XMLDataSource, or AccessDataSource control. Conversely, a SqlDataSource control can have its output rendered by a GridView, DetailsView, DataList, or DropDownList data-bound control. Having noted that flexibility, data controls are optimized for either tabular (relational) or hierarchical (tree) data.

Data controls are optimized for one of two ways to organize information, as discussed in Chapter 7. The first type is relational and the second is hierarchical. Although there can be some crossover in functionality, the division of the controls is described in the following table.

 

Relational

Hierarchical

 

 

 

Data Source Controls

SQLDataSource

XmlDataSource

 

AccessDataSource

SiteMapDataSource

 

ObjectDataSource

 

Data-bound Controls

GridView

TreeView

 

DataList and Repeater

Menu

 

DetailsView and FormView

SiteMapPath

 

 

 

Chapter 8

Both data source and data-bound controls have functionality (like writing to a database) built into their code and you can specifically turn on any or all of those behaviors. For example, in Chapter 7 you enabled paging and sorting. Most of this chapter discusses how to turn on the writing behaviors.

Before diving into details, let us clarify some terminology surrounding writing data. First, writing actually means changing data, as opposed to just creating it. That means that writing includes changes to existing records, creating new records, and deleting existing records. ASP.NET 2.0 uses some industrystandard language for control properties. Changing an existing record is called an UPDATE, and creating a new record is called an INSERT or INSERT INTO. DELETE means removing an entire record from the database. Note that if you want to delete one value from an existing record (for example the date of birth of one player), you would UPDATE that player’s record with a change of the birth date value from a date to NULL. The term SELECT, which you used in the last chapter, means reading data (no changes). ASP.NET 2.0 controls add three additional terms that are used to accept a user’s actions. NEW means to switch to a view of a control that allows the user to enter data for a new record. This action would be followed by create, which actually sends the SQL INSERT INTO instruction to the database. And last, EDIT means switch to a view wherein the user can change a record’s data. That would be followed by a click on UPDATE to actually execute the updating instruction.

Options for Writing Data

Not all data controls support writing. Of the data source controls, all support writing data except for the SiteMapDataSource. But among the data-binding controls there are more limitations. The selection lists (DropDownList and ListBox) do not support writing. The new ASP.NET 2.0 data-bound controls support the best methods of writing data: GridView, DetailsView, and FormView. However, GridView can only update existing records, not create new records. DataList and Repeater can be used to write data, but because they are older controls in many cases they must use the older ASP.NET 1.1 techniques.

GridView does not support the creation of new records. But GridView can easily open a DetailsView control (as you practiced in Chapter 7) and that DetailsView can create a new record.

DataKeyNames

At the time you enable some types of data writing, VWD will add a property to the data-bound control named DataKeyNames. The purpose is to hold both old and new values of a field so that the writing can be performed correctly. To understand this role, imagine that you have a table of comments about Wrox United games named MatchReports. In the table you have as the first field (as most tables do) a field that contains an ID number unique to each row. You call it MatchReportID, and it gets values of 1, 2, 3, and so forth, as fans send in reports about matches. Now say that there was a mix-up and the administrator has to change the ID of a report, say from 20 to 19. When the administrator makes the change he starts by selecting which record to change. ASP.NET 2.0 will store that record’s ID value in a parameter just like it did in Chapter 7 when you used a GridView as a master control. Next the administrator changes the value of the ID field. When he sends that command to the database it will look something like the following:

UPDATE MatchReports SET MatchReport=19 WHERE MatchReport=@MatchReportID

266

Writing Data

Notice that there is the name of the field to change (MatchReportID) and the new value (19). That command also holds an identification of which record to change, something like WHERE MatchReportID= @MatchReportID. But there is a conflict because you have two potential values that could go into @MatchReportID: the old one as saved by the GridView (the value of 20) and the new one that the administrator entered (the value of 19).

DataKeyNames solves this problem by creating a dictionary that keeps two values for fields in its list. One value is the old and one is the new. When a writing command is issued to a database, ASP.NET uses its smarts to supply the new value from DataKeyNames for the SET part of the command and to use the old value from DataKeyNames for the WHERE part of the command. It would be wasteful and slow to load up the DataKeyNames dictionary with every field, particularly because most fields will not raise conflicts. VWD automatically adds to the DataKeyNames those fields that are structured as unique in the database. You can add others, but VWD usually gets it right. In summary, DataKeyNames holds names of fields for which ASP.NET 2.0 must remember both old and new values. When using VWD you rarely have to change DataKeyNames.

Changing Existing Records

The capability to change an existing record can be turned on with two simple steps using VWD. When you create a data source control you go through a panel in the wizard that asks you to select the table and columns (see Figure 8-1).

Figure 8-1

There is also an Advanced button that gives you the option to tell VWD to generate INSERT, UPDATE, and DELETE statements (see Figure 8-2). This simple step enables the UPDATE behavior of the data source

267

Chapter 8

control. Also, checking Use optimistic concurrency will reduce conflicts of two updates at once on a busy web site.

Figure 8-2

VWD takes care of all the work for you, fast and without error (we wish we could say the same for the Wrox United strikers). Two changes are made to the data source control. First, an UPDATE statement is added, similar to the following (INSERT and DELETE statements are also added, but those are discussed later):

<asp:SqlDataSource ID=”SqlDataSource1” runat=”server”

...

UpdateCommand= “UPDATE [MyTable]

SET [Field1] = @Field1, [Field2] = @Field2 WHERE [Field1] = @Field1>

...

</asp:SqlDataSource>

The UPDATE statement indicates that you want to change an existing record. You provide the table holding the record (MyTable):

UpdateCommand= “UPDATE [MyTable]

Then you provide a set of field names and the values you want them to contain. ASP.NET 2.0 generally does not specify those values directly in the command; rather, it uses a reference to a parameter that holds the value. References to parameters begin with an at symbol (@) before the parameter’s name, as shown here:

SET [Field1] = @Field1, [Field2] = @Field2

Note the WHERE clause at the end, which specifies which record to modify. The following syntax says to change the record in the database for which the Field1 value matches the value held in the Field1 parameter. You know that the value to match is from the parameter because you use @ before the field

name, which directs ASP.NET 2.0 to get the value from the parameters list. Without the WHERE clause the update would change all of the records to have the new values the user entered.

WHERE [Field1] = @Field1

268