Creating HTML Programatically

Download Report

Transcript Creating HTML Programatically

Creating HTML Programatically
1
Objectives
You will be able to


Invoke C# code on the server from an ASP.NET page.
Write C# code to create HTML output for an ASP.NET
page dynamically.
2
Example

We will use C# code to output the
current date and time each time a page
is requested by a browser.


Later we will extend the example to show
dynamically created controls.
Start up Visual Studio and create a new
C# ASP.NET empty web site.

Date_Time_Demo
3
New Empty Web Site
4
Add New Item
5
Default.aspx
6
Boilerplate Created by Visual Studio
7
Customize the Boilerplate

Set the title to a meaningful name:
Date Time Demo

Add a top level heading inside the <div>
tags:
<h1>Creating HTML Programatically</h1>
8
Customized Boilerplate
9
Try it!
Title
Heading
10
Server Code

We can add tags to the ASP.NET source
to be processed on the server as the
code is translated into pure HTML.
<%

Between the <%


...
%>
%> tags include normal C# code.
Typically function calls
Output goes into the HTML stream at that point.
11
Invoking Server Code
= says to insert the text produced by the code
into the HTML, replacing the <% %> tags.
12
Server Code Output in Chrome
View source on the browser.
13
What the Browser Received
14
Response.Write()

The = inside <% %> is shorthand for
Response.Write( );


Response is an object that embodies the
response that will be sent back to the
browser in response to the current
request.
Its Write() method inserts text into the
HTML output at the current position.
15
Server Code Shown Directly
16
The Design View
Server code output is not shown at design time.
17
Page in Chrome
18
A Code Behind Function
Note: This is not an event handler.
19
Invoking Code Behind Function
20
Page in Chrome
21
Page_Load

What would happen if we did the Response.Write in
the Page_Load event handler?
22
Remove the <% ... %> Tags
23
HTML Output from Page_Load
24
Creating HTML Programatically

We can invoke a function in the code
behind file from any place in a .aspx file
to output any HTML



using Response.Write( ).
The HTML can be determined at run time
from user inputs, database contents, etc.
The dynamically created HTML goes into
the page at the point where we invoke
the Response.Write( ) function.
End of Presentation
25