N342 ASPx Code Behind |
Modified: |
We have seen that mixing the user interface (HTML) with the programming logic (JavaScript, etc.) looks bad and is bad; difficult to write and to maintain. We've seen (or will) that the two can be separated using industry standard technologies of XML, XML and JavaScript. Microsoft has developed a technology that is part of what they call .NET, known as the code-behind approach.
The basic idea is to write user interface operations as JavaScript (or other language) functions that are callable from HTML.
Mixing the user interface (HTML) with the programming logic (JavaScript, etc.) is one approach. Below is a typical ASP example which we'll redo later in ASPX.
When the submit button is clicked, the HTML submits the form to the server ASP program which examines the iceCream radio buttons to determine the input.
The Request is used to examine user inputs.
The Response is used to write to the browser.
| simple.htm <form action = "simple.asp" method = "post" runat =
"server">
|
simple.asp <%@ LANGUAGE = JScript %> %> |
On the browser, the above appears as below after submitting.
URL: simple.asp?name=Ray&iceCream=Yes
Ray likes ice cream.
Redoing the above in ASPX.
User interface (simple.aspx at left) is defined by mixed HTML and <asp> tags referencing user interface controls.
For example, a radio button list named iceCream with Yes/No options are displayed by:
<asp:RadioButtonList id = "iceCream" runat = "server">
<asp:ListItem>Yes</asp:ListItem>
<asp:ListItem>No</asp:ListItem>
</asp:RadioButtonList>The browser displayed iceCream control can be accessed in the code-behind.
Logic (simple.aspx.js at right) runs on the server. In this case, the only logic is to handle the form submit button click. The iceCream control is accessed to determine
The server translates the <asp> tags into HTML and JavaScript which are sent to the browser.
| simple.aspx <%@ Page Language="JScript" Src="simple.aspx.js"
</asp:RadioButtonList> <br/>
|
simple.aspx.js import System; |
The server generates and sends to the browser mixed HTML and JavaScript (partial listing at left) to produce the user interface (at right).
| Generated by server. View source to see on browser. | Displayed by browser |
| <form name="_ctl0" method="post" action="simple.aspx"
language="javascript" onsubmit="ValidatorOnSubmit();" id="_ctl0"> <input type="hidden" name="__VIEWSTATE" value="dDwtMTY5MDMxMzI4MTs7PnwsEpe40bqXpmAfq1AtBO2yvaQ6" /> <script language="javascript" src="/aspnet_client/system_web/1_1_4322/WebUIValidation.js"> </script> Name: <input name="name" type="text" id="name" /> <br/> Do you like ice cream? |
For comparison:
| simple.htm <form action = "simple.asp" method = "post" runat =
"server">
|
simple.asp <%@ LANGUAGE = JScript %> %> |
| simple.aspx <%@ Page Language="JScript" Src="simple.aspx.js"
</asp:RadioButtonList> <br/> |
simple.aspx.js import System; |
The code-behind is compiled automatically by the IIS server the first time accessed or compiled by hand below.
To compile the above example using Microsoft Visual Studio .NET 2003:
- Open a command prompt.
- Change the directory to the location of the js (JScript) file.
- Define the .NET SDK path variables, for Visual Studio 2003 it is done by:
C:"\Program Files\Microsoft Visual Studio .NET 2003\SDK\v1.1\Bin\sdkvars.bat"
- Compile simple.aspx.js
jsc /t:library /out:simple.dll simple.aspx.js
In the browser address bar enter the location of simple.aspx file containing the HTML and <asp> tags. Assuming the simple.aspx and simple.aspx.js files are located on virtual directory N342 of homepages.ius.edu:
http://homepages.ius.edu/username/n342/simple.aspx
Code-behind appears to be more work, we had to write an ASPX and a JavaScript file that also had to be compiled; so what's the payoff?
- Separating the GUI (simple.aspx) and logic (simple.aspx.js).
- More abstract and powerful GUI objects. The <asp> tagged objects can be controlled by parameters to produce a variety of functions.
- It is possible to develop your own <asp> objects.
- The resulting HTML produced is reasonably generic, working on most browsers.
- Can use a variety of Microsoft .NET languages (JavaScript, C#, Visual Basic).
- A lot of Web development is done in ASPX.
The main drawbacks are:
- Whereas the client XML/XSL and server ASP as used in class can be tested independently, the client/server code must be tested together, as a single unit. Harder to split user interface and logic development.
- Code-behind generates code that you do not directly control, debugging can be challenging.
- Microsoft controls the complete package of <asp> objects and languages rather than the industry in general.
- Learning to use Microsoft objects doesn't transfer well to other platforms (e.g. servers other than IIS).
.NET has changed database use somewhat to distinguish between database server (such as SQL Server or Oracle) and Access-type databases. We will only examine Access database use.
Note that homepages.ius.edu site is configured for use with .NET and Access.
To write to the database, ASPNET must be given the necessary level of permission to make changes to the directory where the Access database is located.
Failure to grant sufficient permission for Update, Insert or Delete operations result is "Operation must use an updateable query" error.
To grant permission to ASPNET to change files in a directory:
- Open My Computer.
- Locate the directory (e.g. C:\Project).
- Right click on the directory and select Properties.
- Click on the Security tab.
- Add ASPNET.
- Grant ASPNET Full Control.
First, ADO can still be used as long as the ASPx file specifies that the page is to be used in ASP compatibility mode, which reduces threading and the performance of the server.
The following displays the ID of all in the Trader table using ADO.
| readID.aspx | readID.aspx.js | |
| <%@ Page Language="JScript" Src="readID.aspx.js" aspcompat=true Inherits="simpleCodeBehind" %> <form action = "readID.aspx" method = "get" |
import System; import System.Web.UI; import System.Web.UI.WebControls; public class simpleCodeBehind extends Page { protected var conn, rs; public function submitButton_Click( sender : Object, events : EventArgs) : void {
} |
|
| bill shato ray wisman Sally Smith bill clinton |
bill shato<br/> ray wisman<br/> Sally Smith<br/> bill clinton<br/> <form name="ctl00" method="get" action="readID.aspx"
id="ctl00"> |
Accessing database records in non-compatibility mode is somewhat different than before.
The following assumes the Project.mdb and ASPx files in the same directory. The code-behind reads each record from the Trader table and prints the ID field value by:
- Connecting to the Access DB Project.mdb file.
- Creating a data adapter and executing an SQL Select on the connected Access DB.
- Creating a dataset named "simple".
- Filling a data table with the selected records from the Trader table.
- Iterating over all data rows in the data table (i.e. dataTable.Rows.Count) and writing out the ID field of each data row.
| readID.aspx | readID.aspx.js | |
| <%@ Page Language="JScript" Src="readID.aspx.js" Inherits="simpleCodeBehind" %> <form action = "readID.aspx" method = "get" runat = "server"> <asp:button text = "Read ID's" OnClick = "Click" runat = "server"/> </form> |
import System; import System.Web.UI; import System.Web.UI.WebControls; import System.Data; import System.Data.OleDb; public class simpleCodeBehind extends Page { protected var conn : OleDbConnection; protected var dataAdapter : OleDbDataAdapter; protected var ds : DataSet; protected var dataTable, data, strData; protected var row : DataRow; protected var i : int; public function Click( sender : Object, events : EventArgs) : void { conn = new OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source="+ Server.MapPath("Project.mdb")); conn.Open();
conn.Close(); |
Writing database records is simple though ASPNET must have permission to write to the directory containing the Access database file.
The following inserts a record into the Trader table by:
- Connecting to the Access DB Project.mdb file.
- Creating a data table as above except, that with only a single table, can reference by index 0 (i.e. ds.Tables[0]).
- Verifying that ID='Ray' is not in data table.
- If not already in table, executing an SQL Insert on the connected Access DB.
| insert.aspx | insert.aspx.js |
| <%@ Page Language="JScript" Src="insert.aspx.js" Inherits="simpleCodeBehind" %> <form action = "insert.aspx" method = "get" runat = "server"> <asp:button text = "Read ID's" OnClick = "submitButton_Click" runat = "server"/> </form> |
import System; import System.Web.UI; import System.Web.UI.WebControls; import System.Data; import System.Data.OleDb; public class simpleCodeBehind extends Page { protected var conn : OleDbConnection; protected var comm : OleDbCommand; protected var dataAdapter : OleDbDataAdapter; protected var ds : DataSet; protected var dataTable; public function submitButton_Click( sender : Object, events : EventArgs) : void { conn = new OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source="+ Server.MapPath("Project.mdb")); conn.Open(); dataAdapter = new OleDbDataAdapter( "SELECT * FROM Trader where ID='Ray'", conn); ds = new DataSet(); dataAdapter.Fill(ds); dataTable = ds.Tables[0]; if( dataTable.Rows.Count == 0 ) { // ID='Ray' not already in Trader table comm = new OleDbCommand("Insert into Trader (ID) values ('Ray')", conn ); comm.ExecuteNonQuery (); } conn.Close(); } } |
Tables are often part of the user interface. To automate table generation from a database, the GUI object DataGrid can be used.
Notice that the two files refer to the same dataGrid object. The ASPx defines the object <asp:DataGrid and the code-behind fills from the database.
The following displays the ID and Balance from the Trader table by:
- Establishing a connection to the Project.mdb Access file in the directory containing the datagrid.aspx file.
- Executing the SQL on the connected database.
- Filling the data set from the resulting table(s).
- Binding the data set to the DataGrid object.
| datagrid.aspx | datagrid.aspx.js | |||||||
| <%@ Page Language="JScript" Src="datagrid.aspx.js" Inherits="simpleCodeBehind" %> <form action = "datagrid.aspx" method = "get" runat = "server"> <asp:button text = "Read IDs" OnClick = "submitButton_Click" runat = "server"/> </form> <asp:DataGrid id = "dataGrid" runat = "server"/>
|
import System; import System.Web.UI; import System.Web.UI.WebControls; import System.Data; import System.Data.OleDb; public class simpleCodeBehind extends Page { protected var conn : OleDbConnection; protected var comm : OleDbCommand; protected var dataAdapter : OleDbDataAdapter; protected var ds : DataSet; protected var dataGrid : DataGrid; public function submitButton_Click( sender : Object, events : EventArgs) : void { conn = new OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source="+ Server.MapPath("Project.mdb")); conn.Open(); dataAdapter = new OleDbDataAdapter( "SELECT ID, Balance FROM Trader", conn); ds = new DataSet(); dataAdapter.Fill(ds); dataGrid.DataSource = new DataView( ds.Tables[0] ); // Use SELECT dataset dataGrid.DataBind(); conn.Close(); } } |