Presentation is loading. Please wait.

Presentation is loading. Please wait.

ASP Chapter 8 1. Active Server Pages Server-side technology dynamicinteractivedata-driven Enables dynamic, interactive, data-driven web pages languages.

Similar presentations


Presentation on theme: "ASP Chapter 8 1. Active Server Pages Server-side technology dynamicinteractivedata-driven Enables dynamic, interactive, data-driven web pages languages."— Presentation transcript:

1 ASP Chapter 8 1

2 Active Server Pages Server-side technology dynamicinteractivedata-driven Enables dynamic, interactive, data-driven web pages languages Scripting OR compiled languages VBScript, VB, C# Jscript, Java Perl Etc… HTML HTML for display/gathering of data ADO ADO for access to data 2

3 Internet Resources ASP.net http://www.w3schools.com/aspnet/  Good for syntax http://www.codefixer.com/asp-net/tutorials/ http://www.dotnetspider.com/tutorials/AspNet-Tutorials.aspx http://www.learn-asp.net/asptutorials/default.aspx http://vishaljoshi.blogspot.com/2009/05/creating-simple-net-40-web-app-using.html http://www.asp.net/web-forms/overview/getting-started/intro-to-aspnet-controls  Basic ASP.net Controls http://msdn.microsoft.com/en-us/library/tw738475.aspx  Setting up an ASP.net Data Control (Gridview), plus others http://www.extremeexperts.com/Net/FAQ/DiffBetweenServerandHTMLControls.aspx  Difference between ASP.net controls and HTML controls http://geekswithblogs.net/dotNETvinz/archive/2009/04/14/c-and-vb.net-code- converter.aspx http://geekswithblogs.net/dotNETvinz/archive/2009/04/14/c-and-vb.net-code- converter.aspx  Good for converting C# code to VB and vice versa; I’ve used the Developer Fusion version HTML http://www.htmlgoodies.com/primers/html/article.php/3478131 http://www.w3schools.com/html/default.asp 3

4 Basic Steps 4 New ASP.net project (Optional) Create or Customize Site.Master template (Optional) Create or Customize Site.css file (Optional) Create or Customize Default.aspx page Create New webpages (.aspx files) Labels Data Controls Buttons Create Code-Behind (.vb files) Database access, data manipulation Test/Debug

5 Database Access Steps 5 Define program variables for data access objects ConnectionDim connObject = New SQLClient.SQLConnection(…..) Query / CommandDim cmdObject AS New SQLClient.SQLCommand (….., …..) Data ContainerDim drObject AS SQLClient.SQLDataReader  Data Reader  Data Adapter… Create connection to the database Open connObject.Open() Run query/command and store data in program container ExecutedrObject = cmdObject.ExecuteReader Display, Maintain “program container” data via Data Controls Grid ViewmyDataControl.DataSource = drObject Details ViewmyDataControl.Databind() Form View List View… Release objects CloseconnObject.close() cmdObject = Nothing drObject.close()

6 Create New ASP.net Project 6

7 Customize Environment 7

8 Customize Site.Master template (image here: http://business.baylor.edu/gina_green/computer.jpg) http://business.baylor.edu/gina_green/computer.jpg 8

9 Customize Site.Master template, cont… (example images here: http://www.baylor.edu/about/?_buref=1155-90749) http://www.baylor.edu/about/?_buref=1155-90749 9

10 Example 1: View Student Info: Create Webpage Prompt user for search criteria Need to know exact data values Find student information based on search criteria 10

11 Create New Webpage 11 - OR -

12 Add Input Controls to Webpage 12

13 Create Database Access Code 13 'THIS CODE GOES IN THE VB FILE for the View Student Information button (FindStudent.aspx.vb) Protected Sub btnFindStudent_Click(sender As Object, e As EventArgs) Handles btnFindStudent.Click 'Hide controls lblStatus.Visible = False '(1) create an ADO connection object to establish connection to the database 'first define a text string that describes database connection information Dim connectionstring As String = "server=hsb-mis-sql; database=mis4340; integrated security=sspi" 'create the ADO connection object using the connection information described above Dim myConnection = New SqlClient.SqlConnection(connectionstring) '(2) establish the connection to the database myConnection.Open() '(3) setup queries that get student data from database based on values the user entered Dim querystring1 As String = "select * from student where stud_id='" & txtStudentID.Text & "';" Dim querystring2 As String = "select * from student where firstname like '%" & txtFirstName.Text & "%' and lastname like '%" & txtLastName.Text & "';" Dim querystring 'Decide which query to use based on which values the user entered If (txtLastName.Text <> String.Empty Or txtFirstName.Text <> String.Empty) Then querystring = querystring2 Else querystring = querystring1 End If '(4) create an ADO command object that will contain the query command to be executed by the database Dim myCommand As New SqlClient.SqlCommand(querystring, myConnection) '(5) create an ADO container object that will hold data retrieved from database Dim myDatareader As SqlClient.SqlDataReader '(6) execute the command and store results in the datareader container object myDatareader = myCommand.ExecuteReader 'if datareader container is empty, display error message If Not myDatareader.HasRows Then lblStatus.Text = "No Student Found" lblStatus.Visible = True myDatareader.Close() Exit Sub End If '(8) close objects myDatareader.Close() myDatareader = Nothing myCommand = Nothing myConnection.Close() myConnection = Nothing End Sub Define CONN var Create CONN Define CMD var Define CONTNR var Run CMD; Store in CONTNR Release Objects

14 Create Database Access Code, cont… 14 'THIS CODE GOES IN THE VB FILE for the CLEAR button Response.Redirect(Request.Url.PathAndQuery, True)

15 Example 2: View Student Info: Add Data Control 15 Display retrieved student information based on search criteria Use GridView data control for displaying Student data

16 Configure the Gridview Control Formatting 16

17 Data Bind/Display Code 17 'THIS CODE GOES IN THE SAME VB CODE for View Student Information button '(7) bind control to data source, then display data to user StudentGrid.DataSource = myDatareader StudentGrid.DataBind() StudentGrid.Visible = True Display CONTNR Data

18 Example 3: View Student Info: Add More Data Controls 18 Prompt for search criteria Use Dropdown web control for specifying Student ID See http://www.dotnetcurry.com/ShowArticle.aspx?ID=221http://www.dotnetcurry.com/ShowArticle.aspx?ID=221 for how to implement “cascading dropdowns” for Lastname and Firstname

19 Wizard: Configure the Database Connection 19

20 Wizard: Configure the SQL Command 20 Will give us student ID as the key field Will give us a field which is the concatenation of student ID and first/last name for ease of lookup

21 Wizard: Move Data from Program Container to UI (& Bind Data to Dropdown 21 Name of the data source (connection and query) we just created The field from the query that we want displayed in the dropdown The field from the query that we want to use as the selected value from the dropdown

22 Result: ASP.net Generates "Code" to Access Data 22 Will be used by a Command object Will be used as the Data Container object and dropdown control will be set to its values Will be used by Connection object Used DropdownList control & configured its data source via Wizard Ensure DropDownList control has this name

23 Modify Database Access Code 23 In VB Code for View Student Information button, retrieve the selected student from the new dropdown instead of from the text box  i.e., replace txtStudentID.Text with SelectedStudentID.Text

24 Example 4: View Student Info: Add Dropdown Option 24 Add dropdown option for "All Students"

25 Modify Database Access Code 25 Add bold code to the aspx file (DON’T copy last “>”): <asp:DropDownList ID="SelectedStudentID" runat="server" DataSourceID="SqlDataSource1" DataTextField="studentinfo" DataValueField="stud_id" AppendDataBoundItems = "true"> All Students Add a third querystring in VB file to define a query that selects all rows and columns from student table *** See Notes *** Update existing IF-Then-Else in VB file to check for "-1" value (i.e., user selected “All Students”) and assign appropriate query ***See Notes ***

26 Example 5: Edit Student Info Edit student information based on a specific student selected Will use Detailsview Control for updating of data *** could have used Gridview or another control *** 26

27 Add Edit Control to Webpage 27 Change to TRUE if multiple records can be edited Set both to TRUE if you want to allow for Editing AND Inserting of records; also set AutoGenerateDeleteButton to TRUE to allow for Deleting of records.

28 Wizard: Configure SQL Command 28 1 2 34

29 Verify Properties 29 Put a button in the data control that allows user to begin editing record Hide control that allows user to Edit until user clicks the Edit Student Information by StudentID button Prevents user from editing the Stud_ID (primary key) field FindStudent.aspx

30 Data Bind/Display Code 30 'This code goes in the existing btnFindStudent_Click VB code 'add the BOLDED lines to the sections indicated: 'Hide controls lblStatus.Visible = False btnEditStudent.Visible = False EditStudentDetails.Visible = False '(7) bind control to data source, then display data to user StudentGrid.DataSource = myDatareader StudentGrid.DataBind() StudentGrid.Visible = True btnEditStudent.Visible = True 'This code goes in the new btnEditStudent_Click VB code 'Hide the StudentGrid control StudentGrid.Visible = False 'Bind control to its data source, then display the EditStudentDetails control for editing EditStudentDetails.DataBind() StudentGrid.Visible = False EditStudentDetails.Visible = True btnEditStudent.Visible = False

31 Example 6: Navigation Update Site Master template to add, change, or remove menu items—be sure to change the href and the text 31

32 Site Master Navigation Code 32 ….. Home About Our Professors Contact Us ……

33 Additional ASP.net Tips and Features 33

34 Debugging your ASP Code 34 Inserting Breakpoints can help you pause execution at certain points that you specify, so you can examine intermediate steps and better isolate problems To set a breakpoint: Right click on the code Choose Breakpoint Choose Insert Breakpoint. A red dot appears on the left margin and the line of code is highlighted. Click the green Continue button to step through each line of code you marked. To turn off a breakpoint: Click on the red dot in the left margin and the breakpoint will be removed from that command ALSO: I suggest commenting out code instead of deleting UNTIL your code runs error-free

35 Creating Template Columns Good for doing additional customization to your data control Many subsequent tips assume columns have been converted to “template” columns Can manually add the required template tags to the.aspx code -- OR -- Can use data control’s smart tag “wizard” to generate required template tags: From the data control’s smart tag, click the “Edit Fields…” (or “Edit Columns…”) link Select each field one at a time in the lower left corner Click the “Convert this field into a TemplateField” link; click OK. Each converted field will have:  a TemplateField tag  an ItemTemplate tag that will display data in a Label for viewing  an EditItemTemplate that will display data in a TextBox for updating  an InsertItemTemplate that will display data in a TextBox for inserting 1 1 Will NOT be generated for GridView fields—you must use FooterTemplates for inserting into GridviewsFooterTemplates 35

36 Placing Dropdowns in a Data Control 36 1.In the Data Control, change the field that you want to convert to a dropdownlist to a TemplateField (e.g., the “classification” field) TemplateField 2.In the design view of the webpage, underneath the data control, drag/drop a dropdownlist control 3.Configure the dropdownlist’s datasource to SELECT appropriate data from the database a.e.g., select classification + ': ' + name as class, classification from classification order by classification; 4.If the Data Control will allow users to update a row by choosing a value from the dropdownlist, (a) drag/drop the previously-generated asp:DropDownList element inside the EditItemTemplate element for the column, between the beginning and ending tags, (b) remove the existing asp:TextBox tag, (c) then add a Bind attribute to the DropDownList tag. The resulting tag should look similar to this: <asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="SqlDataSource3" DataTextField="class" DataValueField="classification" SelectedValue= > 5.If the Data Control will allow users to insert a row, then (a) drag/drop the previously- generated asp:dropdownlist element inside the InsertItemTemplate element for the column, (b) remove the existing asp:TextBox tag, and (c) add a Bind attribute to the DropDownList tag as described above. If you already created a asp:DropDownList element in step 4, you can simply copy/paste that same information into the InsertItemTemplate section. a.NOTE: if you are using a GridView for inserting a row, you would instead place this information in a previously-created FooterTemplate for the column.

37 Editing, Deleting Data via Gridview Editing & Deleting via GridView works the same as DetailsView 1.Configure the GridView with a datasource  Ensure the SQL Data Source is configured with UPDATE, INSERT, and/or DELETE commands. See previous detailsview slides for how to configure gridview, and generate Delete, Insert, or Update commandsprevious detailsview slides 2.AutoGenerate Edit and/or Delete buttons. Do NOT AutoGenerate Insert button. Inserting via GridView does NOT work the same as DetailsView. Must take additional steps… 37

38 Inserting Data via GridView 1.Convert GridView columns to TemplateField columns if they are not alreadyTemplateField 2.Add FooterTemplate to each column you want user to insert values forFooterTemplate 3.Add additional FooterTemplate column that will contain an ADD button for user to click after entering all values to be inserted. To do this, copy/paste the code below before the element of the GridView: 4.In the GridView properties pane, set the ShowFooter property to True 5.Add the following event handler for the ADD button to the VB file 1 Protected Sub EditStudentDetails_RowCommand(sender As Object, e As GridViewCommandEventArgs) Handles EditStudentDetails.RowCommand 'Insert data if the CommandName associated with the button/link = "Insert" If e.CommandName = "Insert" Then SqlDataSource2.Insert() End If End Sub 6.Add code that puts user’s values into Insert statement parameters 2 1 Be sure to change the bolded GridView AND SQLDataSource names to yours. 2 Example code is in the Notes view of this powerpoint slide. You must change the bolded names to yours. 38

39 Create Footer Templates for Inserts From the data control’s smart tag: 1.Choose the “Edit Templates” link 2.Click the “Display:” dropdown 3.From the drop-down list, for each insertable field, select the FooterTemplate 4.Drag the appropriate input control (i.e. textbox, dropdownlist,…) from the Toolbox into the FooterTemplate box in the Designer area If choosing a DropDownList, be sure to configure the SQL statement for it 5.In the Properties panel, change the (ID) to a friendly name (e.g. txtPin, SelectedClassification, …) 6.Repeat steps 2 – 5 for each additional insertable field 7.When done with all fields, click the “End Template Editing” link In the.aspx code, add the following to the end of each element in the FooterTemplates 1 : Text=' ' In the.aspx code, add the following to the end of each element in the FooterTemplates 1 : SelectedValue=' ' 1 Change the word “classification” to the appropriate column names 39

40 Miscellaneous Tips Adding Popup Datepicker from asp.net textbox Applies when user is adding or updating a Date field Add the highlighted code to the.aspx page that contains the textbox(es) that you want the dates to appear in Place highlighted code below between the existing tags indicated in bold $(function () { $("# ").datepicker(); }); 40

41 Miscellaneous Tips, cont… Make an email address clickable (assume table column named "email") Display image (assume filename stored in column "photofile") Display an image (assume table column named "photofile" stores full pathname of file containing the image) 41 Type of Control Replace existing asp tag for the "email" field with the following: DataList ' NavigateUrl=' '> GridView ' Text=' '> Type of Control Replace existing asp tag for the "photofile" field with the following: DataList ' style="height: 50px; width: 50px" /> GridView ' style="height: 50px; width: 50px">

42 Miscellaneous Tips, cont… Remove gridlines Hide field that you do NOT want users to edit or insert 42 Type of Control Highlight the GridView or Detailsview control GridView Or Detailsview In the Properties area, set Gridlines to None Type of Control Add the highlighted code to the asp BoundField or TemplateField tags for the fields you want to hide (e.g., the WeekBeginningDate field below) GridView … '> '>

43 Miscellaneous Tips, cont… Make text wraparound User-friendly Column Headings 43 Type of Control Add the highlighted code to the existing asp:Button tag in the position you want the new line to start Button Type of Control 1 Data Control must have Datasource assigned to it in.aspx code. GridView Or Detailsview If the column HAS NOT been converted to a TemplateField element, change the HeaderText value to the desired column heading as shown in BOLD below: e.g., If the column HAS been converted to a TemplateField element, change the HeaderText value to the desired column heading as shown in BOLD below: e.g., 1 If data control does NOT have a Datasource configured in.aspx code, you can alias column names in the query that is defined in the VB code that populates the data control

44 Miscellaneous Tips, cont… Change View Mode font sizes Shrink Footer row textbox sizes 44 Type of Control In properties: GridView Or Detailsview Under Appearance, expand Font section and set Size attribute as desired e.g., Smaller Type of Control In each column’s FooterTemplate element: GridView Before the end of the asp:TextBox OR asp:DropDownList tag, add the following: (adjust numbers as desired): Font-Size="8pt" Width="70px"

45 Miscellaneous Tips, cont… Change Edit Mode text box & font sizes 45 Type of Control In Site.css code: GridView Or Detailsview Create a style for your GridView edit mode textboxes (suggest adding this to the end of.css file):.GridViewEditRow input[type=text] { width: 50px; font-size: x-small; } In.aspx code: Add an EditRowStyle element anywhere between the start and end GridView tags similar to the element in BOLD below: …

46 Summary What is ASP? Benefits of ASP.net Key objects involved in database access Key steps involved in database access Creating a simple data-driven web application Retrieving data from database Editing data via data controls 46


Download ppt "ASP Chapter 8 1. Active Server Pages Server-side technology dynamicinteractivedata-driven Enables dynamic, interactive, data-driven web pages languages."

Similar presentations


Ads by Google