Tuesday, September 15, 2009

Simple Javascript in .Net

There is a bit difference between writing javascript in PHP vs .Net and in .Net you have to register the javascript that you are going to use.

Compare to .Net, in PHP you may declare your javascript code at header page and then used it while you display your page.

Here is how to write a simple Javascript in .Net.

In this sample (in VB.Net), you will create a page with a button inside it. When you press this button it will display a confirmation text




Now, create a new page, for this example, i just create Default.aspx

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
 </div>
<asp:Button ID="Button1" runat="server" Text="Show Confirmation" />
</form>
</body>
</html>



Next in Default.vb.aspx

Imports System.Web.UI.ClientScriptManager

Partial Class _Default
Inherits System.Web.UI.Page

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

Dim scriptText As String

scriptText = "return confirm('Do you want to submit the page?')"

ClientScript.RegisterOnSubmitStatement(Me.GetType(), "ConfirmSubmit", scriptText)
End Sub
End Class



Please concentrate on "ClientScript", here we register the script on submit event. On the next sample, i will show you how to register a block of javascript codes and we can used it later on :)