Skip to content

ASP.Net Webform: Add HTML and javascript dynamically

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?

Answer

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.