Introduction
description
Transcript of Introduction
Beginning Web Site DevelopmentModule 2 – Web DataBuilding Data-Driven SitesWith ASP.NET and
C# Version
IntroductionTarget audience
New to programming but want to build a dynamic data-backed Web site
PrerequisitesBasic understanding of HTML, familiarity with Web interfacesCompleted “Beginning Web Site Development Module 1”
ExpectationsLearn the basics of building dynamic data-backed Web sites with Visual Web Developer Express and ASP.NET 2.0
AgendaDynamic, data-driven sitesUsing SQL Server 2005 Express
Creating and using local databasesStructured Query Language (SQL)
Talking to a database with SQLData binding
Binding ASP.NET controls to data
Dynamic Web SitesMany sites today are dynamic and interactive
Display content that is updated frequently
News sites, sports sites, stock analysis sitesAllow clients to interact with site
Shopping sites, internet portals, auction sitesInteraction requires storage…
Saving client-entered dataWhere should user-entered data go?
Client BrowserWeb Server
AddPoem.aspx
AddPoem.aspx.cs
?
Saving client-entered dataProblem: interactive Web pages need a place to store dataSolution: relational database
Store data in tabular format (think spreadsheet)Handles multiple users simultaneouslyStandard language (SQL) and many tools for manipulating data
SQL Server 2005 ExpressVWD Express installs SQL 2005 Express
Local file-based database engineFull SQL support, databases up to 4GBEasy to deploy – copy database file (.mdf) to deployment server
Creating a databaseAdd SQL 2005 Express database
Stores data in tables you define Rightclick
Database tablesDatabases store data in tables
Conceptually similar to spreadsheets
Each table is described as a collectionof columns, each storing a specific type of data
A table contains rows of data that conform to the table description
Defining a tableCreate table(s) to store data
Separate column for each attributeUnique ID column
Rightclick
Identity columnsIdentity column
Column storing a unique number for each row
Good practice to have an identity column
Improves performance, adds flexibilityUnique ID generated for each new entry
Filling tables with dataYou can add data to tables you create
Initial seed data or complete data for tables that store read-only data (like a list of items and their prices)
Rightclick
Creating a SQL 2005 Express Database
• Creating the initial database• Adding tables• Specifying identity columns• Populating table data
SQLStructured Query Language (SQL)
Standard way to retrieve data from and modify data in a databaseBasic understanding necessary to use ASP.NET data controls
Four standard operations for manipulating and retrieving data
SELECT
INSERT
UPDATE
DELETE
Testing queriesVWD Express Database Explorer provides query builder
Rightclick
RunQuery
Tables in querylisted here
Columns in querylisted here
Query text
Query results
SELECTing dataSQL method for retrieving data is SELECTSELECT ID, Author, Quote FROM Quotes
Column names Table name=
Constraining with WHERECan add criteria to constrain results of SELECT with WHERE clauseSELECT ID, Author, Quote FROM Quotes WHERE (Author = 'William Shakespeare')=SELECT ID, Author, Quote FROM Quotes WHERE (Author LIKE '%ea%')=
INSERTing rowsSQL method for inserting rows is INSERT
INSERT (Author, Quote) INTO Quotes VALUES ('Me', 'Life is good!')
Column names Table name
Values to insert
UPDATEing rowsSQL method for updating rows is UPDATE
UPDATE Quotes SET Author='Joe' WHERE ID=3
Table name New column value(s)
Constraint (which row(s) )
DELETEing rowsSQL method for deleting rows is DELETE
DELETE FROM Quotes WHERE ID=3
Table name
Constraint (which row(s) )
Interacting with a database using SQL
• Selecting data• Inserting data• Updating data• Deleting data
Data bindingData binding
A mechanism for displaying and modifying dynamic data from a Web page
ASP.NET supports data bindingCan point controls to database table as source for dataDisplayed content drawn from tableInterface for modifying data built into some controls (update, delete, insert)
Data bindingClient Browser Web Server
Default.aspx
Quotes DatabaseData-
binding
Binding controls to dataSeveral ASP.NET controls designed to bind to data
GridViewDisplay/edit a database table as a grid
DetailsView Display one table row at a time, insert new items
BulletedList Display a list of items from a table
Many more …
SqlDataSource controlSqlDataSource control handles data retrieval, inserts, updates, and deletes
Acts as bridge between database and data-bound controlContains SQL statements to perform database calls<asp:SqlDataSource ID="QuotesDataSource" runat="server" SelectCommand="SELECT ID, Author, Quote FROM Quotes" ConnectionString="…"/>
Adding a GridView
1. Set page to Design mode
2. Open Database Explorer3. Drag table onto page4. Select desired options5. Optionally Auto Format…6. Edit Columns and setID column Visible=false
Generated source<asp:GridView ID="GridView1" runat="server" AllowSorting="True" AutoGenerateColumns="False" DataSourceID="SqlDataSource1" EmptyDataText=“No records."> <Columns> <asp:BoundField DataField="ID" HeaderText="ID" ReadOnly="True" SortExpression="ID" Visible="False" /> <asp:BoundField DataField="Author" HeaderText="Author" SortExpression="Author" /> <asp:BoundField DataField="Quote" HeaderText="Quote" SortExpression="Quote" /> </Columns></asp:GridView><asp:SqlDataSource ID="SqlDataSource1" runat="server" SelectCommand= "SELECT ID, Author, Quote FROM Quotes" ConnectionString= "<%$ ConnectionStrings:QuotesConnectionString1 %>"/>
<configuration> <connectionStrings> <add name="QuotesConnectionString1" connectionString="Data Source=… " providerName="System.Data.SqlClient" /> </connectionStrings></configuration>
web.configDefault.aspx
GridView declaration
BoundFields for columns
SqlDataSource declarationSQL query to retrieve dataConnection string pointingto local Quotes.mdf file
Adding a GridView
• Adding a GridView to display table data• SqlDataSource control• Enabling sorting and paging• Formatting the GridView
SQL parametersSQL supports parameters to fill values in dynamically
SQL Server syntax is @varnameBefore executing statement, parameters must be associated with values
UPDATE Quotes SET Author=@Author WHERE ID=@ID
parameters
SqlDataSource parameters
How to associate parameters with SqlDataSource
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ConnectionStrings:QuotesConnectionString1 %>" SelectCommand="SELECT [ID], [Author], [Quote] FROM [Quotes]" UpdateCommand="UPDATE Quotes SET Author=@Author, Quote=@Quote WHERE ID=@ID" DeleteCommand="DELETE FROM Quotes WHERE ID=@ID"> <UpdateParameters> <asp:Parameter Name="Author" Type="String" /> <asp:Parameter Name="Quote" Type="String" /> <asp:Parameter Name="ID" Type="Int32" /> </UpdateParameters> <DeleteParameters> <asp:Parameter Name="ID" Type="Int32" /> </DeleteParameters></asp:SqlDataSource>
Add Updateand Deletecommands with parameters
List parameternames and types
Note: Parameters should always be named the same as the correspondingcolumn names to work properly with the GridView and DetailsView controls
GridView updates and deletes
Once your SqlDataSource has Update and Delete commands, the GridView can be enabled with Update and Delete features
Must set DataKeyNamesto identity column name to support Update/Delete
GridView updating
Inserting with a DetailsView
DetailsView provides insert featureCan also be used to display/update/delete one row at a time
Configure new data source
Inserting with a DetailsViewAdd InsertCommand to data source
Enable Inserting and set DefaultMode=Insert<asp:SqlDataSource ID="SqlDataSource2" runat="server"
ConnectionString="<%$ConnectionStrings:QuotesConnectionString1 %>" SelectCommand="SELECT [ID], [Author], [Quote] FROM [Quotes]" InsertCommand="INSERT INTO Quotes (Author, Quote) VALUES (@Author, @Quote)"> <InsertParameters> <asp:Parameter Name="Author" Type="string" /> <asp:Parameter Name="Quote" Type="string" /> </InsertParameters></asp:SqlDataSource>
Inserting with a DetailsView
Updating, Deleting, and Inserting
• Enabling GridView Updating and Deleting• Using a DetailsView for inserting
SummaryInteractive sites make the internet what it is todayVWD Express includes database engine
SQL Server 2005 ExpressASP.NET supports data binding
Display database contentUpdate, insert, delete
ResourcesVWD 2005 Express home
http://msdn.microsoft.com/vstudio/express/vwd/default.aspx
SQL 2005 Express homehttp://msdn.microsoft.com/vstudio/express/sql/default.aspx
Writing Transact-SQL Statements Tutorial
http://msdn2.microsoft.com/en-us/library/ms365303.aspx
ASP.NET 2.0 QuickStart Tutorialshttp://quickstarts.asp.net/QuickStartv20/aspnet/Default.aspx