0

I need a ASP.net application which is only kind of "pageDisplayer" from content which is coming from an API. So I choose ASP.net Webform and tried the following:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="PMLetterAcceptance.WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <asp:Literal runat="server" id="JavaScript"></asp:Literal>
</head>
<body>
    <form id="letterform" runat="server">
        <div>
            <%= pageContent %>
        </div>
    </form>
</body>
public partial class WebForm1 : System.Web.UI.Page
{
    protected string pageContent = "";

    protected void Page_Load(object sender, EventArgs e)
    {
       ...// here I fetch the html and javascript content from the API

       dynamic json = Json.Decode(streamReader.ReadToEnd());
        if (json.status != "OK")
            pageContent = json.error;
        else
            pageContent = json.html;
        JavaScript.Text = json.script;
    }
 }

The html content and the script are loaded correct but I cannot access DOM elements in the javascript. The javascript looks like that

(function()
{
    function processForm(e)
    {
         ... // Here I want to do some stuff before sending the form
    }

    let form = document.getElementById('letterform');
    if (form.attachEvent)
        form.attachEvent("submit", processForm);
    else
        form.addEventListener("submit", processForm);
})();

No I get the error "form is null". For me it looks like the javascript is executed before the DOM is ready. But how can I change this to make it work like expected?

4
  • Odd, because letterform is already on the page. Can you try putting the JS (literal) at the bottom of the page, before the closing body tag? Does, the JS include script tags? Commented May 20, 2021 at 10:13
  • In my eyes there is a mistake in your javascript. Your code is designed for executing when the browser reach the lines. Commented May 20, 2021 at 10:17
  • Oh my god. Sometimes it can be so easy. Putting it at the end of body works fine. thanks a lot Commented May 20, 2021 at 10:20
  • Added as answer. Can you vote for it please? I'm actually not going for the points, there's just no way to know that a question has been answered in the comments. Drives me a bit nuts checking out questions that seem to have no answer but do. Commented May 20, 2021 at 10:41

1 Answer 1

1

Try putting the JS (literal) at the bottom of the page, before the closing body tag. That way, the HTML will be loaded before the JS tries to find elements.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.