views:

133

answers:

3

Hi there,

I'm probably missing out on something fundamental here but it seems rather tricky and confusing to me so here goes...

to demonstrate the issue I have the following example .aspx page

<%@ Page Language="VB" %>

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

<script runat="server">
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
    Response.Write("<script type=text/javascript>alert('Alert from response.write')" & ";</sc" & "ript>")
End Sub

Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs)
    Response.Write("<script type=text/javascript> helloWorld(); </sc" & "ript>")
End Sub

Protected Sub Button3_Click(ByVal sender As Object, ByVal e As System.EventArgs)
    Response.Write("<script type=text/javascript> helloWorld(); </sc" & "ript>")
End Sub
</script>

<html xmlns="http://www.w3.org/1999/xhtml"&gt;
<head runat="server">
<title>Untitled Page</title>
<script type="text/javascript">
    function helloWorld() 
    {
        alert('hello!');
    }
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
    <asp:Button runat=server ID="Button1" text=1 OnClick="Button1_Click" />
    <asp:Button runat=server ID="Button2" text=2 OnClick="Button2_Click" />
    <asp:Button runat=server ID="Button3" text=3 OnClick="Button3_Click" OnClientClick="helloWorld();" />
    <asp:Button runat=server ID="Button4" text=4/>
</div>
</form>
</body>
</html>

So, I have 3 buttons, the first calls response.write to perform a JS alert.. this works. The second tries to call helloWorld() that is defined in the head tag.. this does not work. The third called helloWorld() both in the response.write and also the onClientClick() - only the onClientClick works.

Could someone explain why I can't call helloWorld() using the response.write method?

Cheers :D

A: 

I think Response.Write is probally wiping the the helloWorld() definition in the PostBack. Try inserting the script tags into the HTML using a PlaceHolder. Rich

kim3er
I see your point, it's rendering a new page when I click the button. Cheers.
Tabloo Quijico
+1  A: 

You are calling helloWorld before the HTML containing the function has even been downloaded.

Define your functions before you call them.

(And use a validator - you can't have <script> tags outside the head or body.)

David Dorward
A: 

The server side click events run before any content is rendered. So the Response.Write generate the script elements before even the html element is written in the response. Use View Source in the browser to see what has been written.

Try searching the help docs or MSDN for "ASP.NET page lifecycle" to learn what is going on here.

AnthonyWJones