Home > Mobile >  Call code from code behind on page load in ASP.net?
Call code from code behind on page load in ASP.net?

Time:07-24

I am simly trying to call the code from a code behind immediateky, as soon as the page loads.

How can I accomplish this? I tried making an invisible button and then tried clicking that on load, but that is not working for me. Hoping there is a simpler way.

This is the code behind. Filename is CodeBehind.aspx.cs:

    public partial class DoTheThing: InjectablePageBase
    {
        private string GetURL(Object sender, EventArgs e){
             // RUN MY CODE
        }
    }

And this is the relevant part of the .aspx file:

<%@ Page Language="C#" AutoEventWireup="false" CodeBehind="CodeBehind.aspx.cs" Inherits="Test.GuideMe.DoTheThing" MasterPageFile="~/Theme/Framework.Master"%>
<asp:Content ID="Content2" runat="server" ContentPlaceHolderID="PageContentPlaceHolder">
<script Language="JavaScript">
    window.onload = function() { document.querySelector('#invisibleGuideMeBtn').click() };
</script>

<div>
    <a id="invisibleGuideMeBtn" href="#" onclick="<%= GetURL %>" target="_self"  runat="server">The Link</a>
    <%-- <asp:Button ID="invisibleGuideMeBtn" Text="Edit" onclick="GetURL" CssClass="btn btn-primary"/> --%>
    <%-- <asp:LinkButton id="invisibleGuideMeBtn" Text="" OnClientClick="GetURL" runat="server"/> --%>
    <%-- <u><b><asp:LinkButton OnClick="GetGuideMeURL" runat="server">Click here</asp:LinkButton></b></u> --%>

</div>
</asp:Content>

Above are 4 different ways I tried clicking a button/link to call the code behind. I either get the error message:

Uncaught TypeError: Cannot read properties of null (reading 'click')
    at window.onload

OR the error: The function GetURL cannot be found

CodePudding user response:

I came across this error once and the following fixed it, not sure if it'll work for you.

I used <%#CSCodeName() %> this format to get the code behind and sometimes I'd have to add a semi-colon like this <%#CSCodeName(); %>

CodePudding user response:

so, the page is to load, then display and THEN we are to click a button and run some code.

but, that means the page will re-load, and after page load, your code runs again then right?

so, there has to be additional information to correctly answer this question. You can certainly with ease trigger some code, and even have such code click a hidden button to run your code stub in code behind. But that of course will cause the page to post back, re-load, and now we back to after the page loads - which it just did, we going to run the code again?

So, what criteria are you to use after page load to run, or not run the code you want again? Without this information, then after page load, we click that hidden button, and then page will load again, and after page load, the code will click the button again and again, then right?

  • Related