Search code examples
javascriptasp.netonloadcode-behinddocument-body

Why does my document body onload event occurs continously?


I have a javascript function that causes a click event on a button, which activates a function in the code-behind. I want this click/function to occur once when the page first loads, however I can't work out why the onload event seems to be occurring continuously.

The Figure1.aspx code is shown below

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Figure1.aspx.cs" Inherits="Figure1" %>

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
    <title>Page 1</title>
</head>

<body style='margin: 0px; overflow: hidden;' onload="getLocation()">
    <script>
        function getLocation() {
            document.getElementById('insertMyLocationButton').click();
        }
    </script>

    <form id="form1" runat="server">
        <div>
            <asp:Button ID="insertMyLocationButton" runat="server" Text="insertMyLocation" 
                onclick="insertMyLocation2" ClientIDMode="Static" style="display:none;"/>
            <p><asp:Literal runat="server" Id="insertResult">1</asp:Literal></p>    
       </div>
    </form>

</body>
</html>

My Figure1.aspx.cs is as follows

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Figure1 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void insertMyLocation2(object sender, EventArgs e)
    {
        insertResult.Text = Convert.ToString(Convert.ToInt16(insertResult.Text)+1);
    }
}

The serverside function insertMyLocation2 in this code updates the string in the paragraph tag with id inserResult, and it can be seen that it continuously updates, even though the only call shoudl be from the onload event.

I woudl expect only a single onload event call.

Thanks for helping a newbie.


Solution

  • I would handle the "click" in the code behind file like this:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            ClientScript.RegisterStartupScript(this.GetType(), "",
                                               "<script language=javascript>getLocation();</script>");
        }
    }
    
    protected void insertMyLocation2(object sender, EventArgs e)
    {
        insertResult.Text = Convert.ToString(Convert.ToInt16(insertResult.Text) + 1);
    }
    

    Then you need to remove from the body tag:

     onload="getLocation()"
    
     <body style='margin: 0px; overflow: hidden;'>
    

    Then the page should show 2 and stops.

    Why it does what it does was answered in the comment above. Hope this helps.