Skip to content

ASP.Net Webform: Add HTML and javascript dynamically

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

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

<!DOCTYPE html>

<html xmlns="">
<head runat="server">
    <asp:Literal runat="server" id="JavaScript"></asp:Literal>
    <form id="letterform" runat="server">
            <%= pageContent %>
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;
            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 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);
        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?


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.