Tuesday, April 29, 2008

Javascript in VB.Net webpage

Using javascript in an ASP.net webpage can sometimes do small wonders. It can reduce some coding and also can be efficient at times. Lets look at an example on how to do this.

Consider this ASP.net page.



<%@ 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>Javascript-ASP.NET Example</title>
</head>
<body>
   <form id="form1" runat="server">
   <div>
        <asp:Button ID="Button1" runat="server" Text="Show Javascript Alert" />
   <br />
   </div>
   </form>
</body>
</html>


The page has only one (Just to keep things simple) with the label "Show Javascript Alert". Now before doing some tasks when the user clicks on the button you may sometimes want to display a message to the user or may even ask for a confirmation whether to go ahead. This can be easily done adding a javascript alert and associating it with the button.

Lets say you want to use a javascript alert 'if (! confirm('Continue?')) return false;' to ask the user 'Continue?' and do something if user clicks Yes and Do Nothing if No is clicked. Go to the VB source file of the page and at the Page_Load () event add 'Button1.Attributes.Add("OnClick", "javascript:if (! confirm('Continue?')) return false;")'. This is considering that the Button's id is Button1. Now view the page in your browser and click on the button , you should see the Javascript alert.

What happens here:

If you go back and have a look at the Default.aspx page source, you'll see


<asp:Button ID="Button1" runat="server" Text="Show Javascript Alert" />
.

This is the line of code which creates the Button and labels it "Show Javascript Alert". But as you can see there's no OnClick event. So the button doesn't do anything till this point.

Now go to the Default.aspx.vb to view the back end VB code of the page. We've added '

Button1.Attributes.Add("OnClick", "javascript:if (! confirm('Continue?')) return false;")

' in the Page_Load () event. This is where the buttons 'OnClick' even is defined. One important thing to notice here is that the 'OnClick' doesn't replace the 'Button1_Click' event of the button, in fact 'Button1_Click' gets executed right after the user responds to the OnClick. So we can put whatever action we want to perform if the user says 'Continue' in the Button1_Click() event.

Now load the page in your browser and view the HTML source. Most likely you'd see something like this :

<input type="submit" name="Button1" value="Show Javascript Alert" onclick="javascript:if (! confirm('Continue?')) return false;" id="Button1" />


As you can see the 'Button1.Attributes.Add' does the magic here. It lets you add methods to a control. Here we just added the 'OnClick' to the control Button1.

0 comments: