Friday, 2 December 2011

Web Forms in ASP.NET

In ASP.NET Web forms, it is essential to write all the server controls within the <form> tag and runat="server" attribute must be included in it. This attribute shows that the form is to be processed on the server. Also it indicates that the controls enclosed in the <form> tag can be accessed by server scripts.

For instance:
<form runat="server">

...HTML + server controls

</form>
If you don't specify the action attribute, it will be ignored as the form is always submitted to the page itself. If method attribute is left out, by default it will be set to method="post". Other attributes like name and if are also automatically assigned by ASP.NET if you don't mention them. Important point to keep in mind here is that an .aspx page can have only one <form runat="server"> control.
If you leave out name, method, action and ID attribute, the .aspx page will look as follows if you view the source:
 <form name="_form1" method="post" action="index.aspx" id="_form1">

...some code

</form>

Submitting a Form

A button is used mostly to submit a form. The format of the Button server control is as follows in ASP.NET:
<asp:Button id="id" text="label" OnClick="sub" runat="server"/>
Here the id attribute sets a unique name for the button and the text attribute assigns a label to the button. The onClick event handler sets a named subroutine to execute.
In the following example we declare a Button control in an .aspx file. A button click runs a subroutine which changes the text on the button:
<script runat="server">
Sub submit(Source As Object, e As EventArgs)

button1.Text="You clicked me!"

End Sub

</
script>
<
html>
<
body>
<
form id="Form1" runat="server">
<
asp:Button id="button1" Text="Click me!" runat="server"
OnClick
="submit" />
</
form>
</
body>
</
html>

Try it yourself 

<script  runat="server">
Sub submit(Source As Object, e As EventArgs)
   button1.Text="You clicked me!"
End Sub
</script>


<html>
<body>

<form runat="server">
<asp:Button id="button1" Text="Click me!" runat="server" OnClick="submit" />
</form>

</body>
</html>

 



No comments:

Post a Comment