PROWAREtech
ASP.NET: Tutorial
ASP.NET Tutorial - Page 2 (.NET Framework).
<%@ Page Language="VB" %>
<script runat="server">
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
lblHello.InnerHtml = "Hello " & txtName.Value
End Sub
</script>
<html>
<head><title>Hello</title></head>
<body>
<form id="form1" runat="server">
Enter your name:<input type="text" id="txtName" runat="server" />
<asp:Button ID="Button1" runat="server" Text="Submit Query" OnClick="Button1_Click" />
</form>
<span id="lblHello" runat="server"></span>
</body>
</html>
The previous example output this to the browser:
<html>
<head><title>Hello</title></head>
<body>
<form method="post" action="Default.aspx" id="form1">
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwULLTE5Njc0MTYxMzYPZBYCAg..." />
<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEdAAN/m5g0b2a+
zaHVWk2+8rIIozoJZpuXxkpOVJKRbHyuHs34O/GfAV4V4n0wgFZHr3dFXqNPfC4dZJB+r2ifPcYeeQlEiGzksAE1NVfO/nb6Ag==" />
Enter your name:<input name="txtName" type="text" id="txtName" value="HARRY" />
<input type="submit" name="Button1" value="Submit Query" id="Button1" />
</form>
<span id="lblHello">Hello HARRY</span>
</body>
</html>
Notice that the server-side script/code is gone and that there is VIEWSTATE and EVENTVALIDATION which handle the statelessness of HTTP and prevent injection attacks, respectively. Thanks to the VIEWSTATE, web forms give the page a life cycle and raises events. This is all handled automatically and is transparent to the programmer.
Another example: turn a decimal number into binary.
<%@ Page Language="VB" %>
<script runat="server">
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
If Page.IsPostBack Then
If IsNumeric(txtNumber.Value) Then
lblBinary.InnerHtml = ""
Dim input As UInt64 = txtNumber.Value
Dim bit As UInt64 = 4503599627370496
While bit > 0
lblBinary.InnerHtml &= IIf((input And bit) = 0, "0", "1")
bit /= 2
End While
End If
End If
End Sub
</script>
<html>
<head><title></title></head>
<body>
<form id="form1" runat="server">
Enter a number:<input type="text" id="txtNumber" runat="server" />
<input id="Submit1" type="submit" runat="server" />
</form>
<span id="lblBinary" runat="server"></span>
</body>
</html>
Now, in C#
<%@ Page Language="C#" %>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
ulong input;
if(ulong.TryParse(txtNumber.Value.ToString(), out input))
{
lblBinary.InnerHtml = "";
while (input > 0)
{
lblBinary.InnerHtml = (input % 2).ToString() + lblBinary.InnerHtml;
input /= 2;
}
}
}
}
</script>
<html>
<head><title></title></head>
<body>
<form id="form1" runat="server">
Enter a number:<input type="text" id="txtNumber" runat="server" />
<input id="Submit1" type="submit" runat="server" />
</form>
<span id="lblBinary" runat="server"></span>
</body>
</html>
See Server Controls.
Comment