DEV Community

Cover image for Building Powerful Web Interfaces with WebForms Core Without Writing JavaScript
Elanat Framework
Elanat Framework

Posted on

Building Powerful Web Interfaces with WebForms Core Without Writing JavaScript

Introduction

JavaScript has become an essential part of modern web development. Most interactive web applications rely on JavaScript to manipulate the DOM, handle user interactions, update content, and integrate third-party libraries. Many development approaches also require developers to write and maintain substantial amounts of client-side code, even when the application's primary logic already exists on the server.

WebForms Core (WFC), developed by Elanat, offers a different approach. It allows developers to control and manipulate browser interfaces from the server using a command-based architecture, without requiring them to write JavaScript for their application logic or UI operations.

The central idea behind WebForms Core is straightforward: developers define what should happen on the server, WebForms Core generates the corresponding commands, and WebFormsJS executes those commands in the browser.

This creates a clear separation between command generation and command execution. The server acts as the commander, while the browser acts as the executor.

Importantly, this does not mean that WebForms Core renders the entire interface on the server or maintains a server-side copy of the browser DOM. The browser continues to own and manage its actual DOM. The server simply sends instructions that WebFormsJS interprets and executes against that DOM.

This architecture makes it possible to build interactive interfaces, modify existing HTML elements, create new elements, change styles, handle events, and perform many other UI operations through server-side code.

And developers do not have to write JavaScript to accomplish these tasks.

How WebForms Core Works

WebForms Core uses a server-orchestrated, client-executed architecture.

The developer writes server-side code using the WebForms API. These API calls generate Action Controls, which represent instructions for the browser. The generated commands are then delivered to the client, where WebFormsJS processes and executes them.

The process can be summarized in three steps:

  1. Server-side definition: The developer calls WebForms methods to describe the required UI operations.
  2. Command generation: WebForms Core converts those operations into its compact command format.
  3. Browser-side execution: WebFormsJS receives the commands and applies the corresponding changes to the browser DOM.

For example, a developer can create an HTML element, assign a style, and set its content entirely from C#:

WebForms form = new WebForms();

form.AddTag("Container", "div");
form.AddStyle("Container|<div>", "color: blue; padding: 10px;");
form.SetText("Container|<div>", "Hello from WebForms Core!");

Write(form.ExportToHtmlComment());
Enter fullscreen mode Exit fullscreen mode

The corresponding HTML container can be defined normally in the View:

<div id="Container"></div>
Enter fullscreen mode Exit fullscreen mode

There is no need to write a JavaScript function to create the element, find it in the DOM, assign its style, or set its text. WebForms Core generates the instructions, and WebFormsJS executes them.

The important distinction is that WebFormsJS is still the browser-side execution engine. WebForms Core does not eliminate JavaScript from the browser platform; it eliminates the requirement for developers to write JavaScript for the UI operations handled by WFC.

Building a Chart Without Writing JavaScript

WebForms Core Programming Without Writing JavaScript

A good way to understand the capabilities of WebForms Core is to build something more complex than changing text or modifying a style.

Consider a simple bar chart displaying weekly sales statistics. We can create the entire chart using C# and WebForms Core, without using a JavaScript charting library or writing application-level JavaScript.

The following example uses a reusable extension method to generate the chart.

Controller

using CodeBehind;

public partial class ChartController : CodeBehindController
{
    public void PageLoad(HttpContext context)
    {
        var sales = new List<SaleData>
        {
            new SaleData("Saturday", 80),
            new SaleData("Sunday", 55),
            new SaleData("Monday", 95),
            new SaleData("Tuesday", 40),
            new SaleData("Wednesday", 70),
            new SaleData("Thursday", 30),
            new SaleData("Friday", 50)
        };

        WebForms form = new WebForms();

        form.GenerateBarChart("ChartBox", sales, "Weekly sales");

        Write(form.ExportToHtmlComment());
    }
}

public class SaleData
{
    public SaleData(string day, int value)
    {
        Day = day;
        Value = value;
    }

    public string Day { get; set; }
    public int Value { get; set; }
}
Enter fullscreen mode Exit fullscreen mode

Reusable Chart Extension

The chart-generation logic is implemented as an extension method. This makes it possible to reuse the same functionality in other controllers and applications.

public static class WebFormsChartExtension
{
    public static void GenerateBarChart<T>(
        this WebForms form,
        string inputPlace,
        IEnumerable<T> data,
        string tableName)
    {
        form.AddTag(inputPlace, "b");
        form.AddStyle(
            inputPlace + "|<b>",
            "background-color: #fafafa;border: 1px solid #ddd;padding: 5px;"
        );
        form.SetText("-", tableName);

        form.AddTag(inputPlace, "div");

        string chart = inputPlace + "|.<div>-1";

        form.AddStyle(
            chart,
            "width:600px;height:300px;display:flex;" +
            "align-items:flex-end;gap:15px;padding:20px;" +
            "border:1px solid #ddd;background:#fafafa;"
        );

        string column = chart + "|.<div>-1";
        string bar = column + "|.<div>-1";

        form.Repeat(w =>
        {
            w.AddTag(chart, "div");
            w.AddStyle(
                column,
                "height:100%;display:flex;flex-direction:column;" +
                "align-items:center;justify-content:flex-end;"
            );

            w.AddTag(column, "div");
            w.AddStyle(
                bar,
                "width:60px;border-radius:4px;display:flex;" +
                "align-items:center;justify-content:center;" +
                "background:#4CAF50;"
            );

            w.AddTag(bar, "span");
            w.AddStyle(
                bar,
                "color:white;font-size:12px;font-weight:bold;"
            );

            w.AddTag(column, "label");
            w.AddStyle(
                column,
                "margin-top:8px;font-size:12px;color:#333;" +
                "text-align:center;"
            );
        }, data.ToList().Count);

        int i = 0;

        foreach (var item in data)
        {
            var properties = typeof(T).GetProperties();

            string title =
                properties[0].GetValue(item)?.ToString() ?? "";

            int value = Convert.ToInt32(
                properties[1].GetValue(item)
            );

            column = chart + "|.<div>" + i;
            bar = column + "|.<div>";

            form.SetHeight(bar, value * 2);
            form.SetText(bar + "|.<span>", value.ToString());
            form.SetText(column + "|.<label>", title);

            i++;
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

View

<div id="ChartBox"></div>
Enter fullscreen mode Exit fullscreen mode

This example demonstrates an important capability: WebForms Core can do more than manipulate existing HTML elements. It can construct a complete interface dynamically, including nested elements, styles, and data-driven content.

The chart is generated from server-side data. Its columns, labels, values, and visual structure are all defined through WebForms Core commands.

No chart-specific JavaScript is required.

The extension method also demonstrates how developers can build reusable functionality on top of the WebForms API. Instead of repeating the same sequence of commands throughout an application, they can package that functionality into a convenient method.

This approach can be extended to much more sophisticated UI elements and reusable libraries.

Using JavaScript Libraries Alongside WebForms Core

Load Module with WebForms Core

Not requiring JavaScript does not mean that WebForms Core discourages JavaScript or limits developers to its own UI capabilities.

Quite the opposite: developers can combine WebForms Core with the extensive JavaScript ecosystem whenever they need specialized functionality.

The important architectural point remains the same: the center of control can stay on the server, even when a JavaScript library performs the actual rendering or specialized client-side work.

Let's look at a more advanced example using Chart.js.

Unlike the previous example, this implementation delegates chart rendering to the popular Chart.js library. However, the application still uses C# and WebForms Core to configure and control the chart.

Controller

The following controller loads a JavaScript module, calls its exported methods, supplies chart data, and inserts the generated chart markup into the page.

using CodeBehind;

public partial class ChartJSController : CodeBehindController
{
    public void PageLoad(HttpContext context)
    {
        if (context.Request.Query.ContainsKey("load"))
        {
            Button1_OnClick(context);
            return;
        }

        WebForms form = new WebForms();

        form.SetGetEvent("Button1", HtmlEvent.OnClick, "?load");

        Write(form.ExportToHtmlComment());
    }

    private void Button1_OnClick(HttpContext context)
    {
        WebForms form = new WebForms();

        // Load Module
        form.LoadModule("/script/module/chartjs_module.js",
        [
            "chart_SetType",
            "chart_SetTitle",
            "chart_AddLabel",
            "chart_AddDataset",
            "chart_Render",
            "chart_Clear",
            "chart_Init"
        ]);

        // Clear previous chart data
        form.CallModuleMethod("chart_Clear");

        // Set chart type
        form.CallModuleMethod("chart_SetType", ["bar"]);

        // Set title
        form.CallModuleMethod(
            "chart_SetTitle",
            ["Weekly Sales Statistics"]
        );

        // Add labels
        form.CallModuleMethod("chart_AddLabel", ["Saturday"]);
        form.CallModuleMethod("chart_AddLabel", ["Sunday"]);
        form.CallModuleMethod("chart_AddLabel", ["Monday"]);
        form.CallModuleMethod("chart_AddLabel", ["Tuesday"]);
        form.CallModuleMethod("chart_AddLabel", ["Wednesday"]);
        form.CallModuleMethod("chart_AddLabel", ["Thursday"]);
        form.CallModuleMethod("chart_AddLabel", ["Friday"]);

        // Add datasets
        form.CallModuleMethod(
            "chart_AddDataset",
            ["Production", 5, 8, 12, 7, 10, 6, 11]
        );

        form.CallModuleMethod(
            "chart_AddDataset",
            ["Sales", 12, 19, 3, 5, 15, 4, 9]
        );

        form.SetText(
            "chartContainer",
            Fetch.ModuleMethod("chart_Render")
        );

        form.CallModuleMethod("chart_Init");

        IgnoreAll();
        Write(form.Response());
    }
}
Enter fullscreen mode Exit fullscreen mode

View

<div
    id="chartContainer"
    style="width: 600px; height: 400px;">
</div>

<button id="Button1">Show Chart</button>
Enter fullscreen mode Exit fullscreen mode

The controller does not directly manipulate the Chart.js API. Instead, it communicates with a dedicated JavaScript module through WebForms Core.

This gives the developer a server-side interface for controlling a client-side library.

JavaScript Bridge Module

The module acts as an intermediary between WebForms Core and Chart.js. It exposes a set of methods that can be called from the server.

The Chart.js library itself is loaded only when needed.

// chartjs_module.js

let Chart = null;

let chartData = {
    labels: [],
    datasets: []
};

let chartConfig = {
    type: "bar",
    options: {
        responsive: true,
        scales: {
            y: {
                beginAtZero: true
            }
        }
    }
};

let chartInstance = null;
let chartScriptLoading = null;

function chart_Load()
{
    if (window.Chart)
    {
        Chart = window.Chart;
        return Promise.resolve();
    }

    if (chartScriptLoading)
        return chartScriptLoading;

    chartScriptLoading = new Promise((resolve, reject) =>
    {
        const script = document.createElement("script");

        script.src = "/script/module/chart.umd.min.js";

        script.onload = function()
        {
            Chart = window.Chart;

            if (Chart)
                resolve();
            else
                reject("Chart.js loaded but window.Chart not found");
        };

        script.onerror = function()
        {
            reject("Cannot load Chart.js");
        };

        document.head.appendChild(script);
    });

    return chartScriptLoading;
}

export function chart_SetType(type)
{
    chartConfig.type = type;
}

export function chart_SetTitle(title)
{
    if (!chartConfig.options.plugins)
        chartConfig.options.plugins = {};

    chartConfig.options.plugins.title =
    {
        display: true,
        text: title
    };
}

export function chart_AddLabel(label)
{
    chartData.labels.push(label);
}

export function chart_AddDataset(...args)
{
    if (args.length < 2)
        return;

    const label = args[0];

    const data = args
        .slice(1)
        .map(Number)
        .filter(x => !isNaN(x));

    chartData.datasets.push(
    {
        label: label,
        data: data,
        backgroundColor: "rgba(54,162,235,0.6)",
        borderColor: "rgba(54,162,235,1)",
        borderWidth: 1
    });
}

export function chart_Clear()
{
    chartData =
    {
        labels: [],
        datasets: []
    };

    chartConfig =
    {
        type: "bar",
        options:
        {
            responsive: true,
            scales:
            {
                y:
                {
                    beginAtZero: true
                }
            }
        }
    };

    if (chartInstance)
    {
        chartInstance.destroy();
        chartInstance = null;
    }
}

export function chart_Render()
{
    return `
        <canvas
            id="chartCanvas"
            style="width:100%;height:100%;">
        </canvas>
    `;
}

export async function chart_Init()
{
    try
    {
        await chart_Load();

        const canvas = document.getElementById("chartCanvas");

        if (chartInstance)
        {
            chartInstance.destroy();
            chartInstance = null;
        }

        const ctx = canvas.getContext("2d");

        chartInstance = new Chart(ctx,
        {
            type: chartConfig.type,
            data: chartData,
            options: chartConfig.options
        });

        console.log("Chart Created Successfully");
    }
    catch(er)
    {
        console.error("Error in Chart.js:", er);
    }
}

console.log("ChartJS Module loaded");
Enter fullscreen mode Exit fullscreen mode

This module illustrates how a JavaScript library can be wrapped in a small, reusable interface.

The server does not need to know the internal details of Chart.js. It only needs to know the methods exposed by the module:

  • chart_SetType
  • chart_SetTitle
  • chart_AddLabel
  • chart_AddDataset
  • chart_Render
  • chart_Clear
  • chart_Init

The module handles the library-specific implementation, while the controller determines what chart should be created and what data it should contain.

This separation is particularly useful when building reusable modules. A developer can create a module once and expose a clean set of methods for server-side use in multiple applications.

Two Different Approaches, One Architecture

The two chart examples demonstrate different ways to use WebForms Core.

Capability Native WFC implementation JavaScript library integration
Chart construction WebForms Core commands Chart.js
Main application code C# C#
JavaScript application code Not required Used in the bridge module
UI control Server-side Server-side through module calls
Rendering HTML and CSS Canvas and Chart.js
Reusability C# extension methods JavaScript modules

Neither approach is inherently better. The appropriate choice depends on the requirements of the application.

For relatively simple UI elements, WebForms Core can provide everything needed without introducing an additional JavaScript dependency.

For specialized features such as advanced charts, maps, editors, animation engines, or complex visualization tools, developers can integrate existing JavaScript libraries instead of rebuilding their functionality.

The key is that WebForms Core does not force developers to choose one approach for the entire application.

Building Reusable Libraries Without Making JavaScript Mandatory

One particularly interesting possibility is building reusable libraries on top of WebForms Core.

The first example already demonstrates this concept through a C# extension method. The chart-generation logic is packaged into a reusable method that can be called from different controllers.

The same principle can be used to build much larger libraries.

For example, developers can create server-side libraries for:

  • Charts and data visualization
  • Dynamic tables and data grids
  • Navigation menus and hierarchical menus
  • Form generation and validation
  • Dialogs and notification systems
  • Loading indicators and skeleton interfaces
  • Dynamic layouts and interactive elements
  • Reusable UI components

These libraries can expose convenient server-side APIs while WebForms Core handles the communication and browser-side execution.

JavaScript can remain completely outside the application code when the required functionality can be implemented using WFC commands. If a library needs specialized browser functionality, a JavaScript module can provide that functionality behind the same kind of server-side interface.

This creates an opportunity to build libraries that are primarily controlled from server-side code without giving up access to the browser's JavaScript ecosystem.

The Server Remains the Center of Control

One of the most important characteristics of WebForms Core is where the primary control resides.

In many JavaScript-centered architectures, application logic and UI orchestration are distributed across server-side and client-side code. Developers must coordinate these parts and maintain the communication between them.

WebForms Core offers a different arrangement. The server can define the operations, determine when they should happen, and generate the commands that describe them. The browser executes those commands through WebFormsJS.

Even when an external JavaScript library is involved, the server can remain responsible for deciding what should happen and supplying the parameters.

This does not mean that every operation must run on the server. Browser-side modules can perform specialized tasks, handle internal library state, and execute operations that are more appropriate for the client. The distinction is that these capabilities do not require developers to move the entire UI control model to JavaScript.

WebForms Core is therefore not an alternative to the JavaScript ecosystem. It is a way to control browser interfaces through a server-oriented programming model while retaining the freedom to use JavaScript wherever it provides value.

Conclusion

WebForms Core demonstrates that building powerful interactive web interfaces does not require developers to write JavaScript for every UI operation.

Developers can create elements, manipulate the DOM, define styles, generate data-driven interfaces, and build reusable UI libraries using server-side code. They can also integrate established JavaScript libraries through modular interfaces whenever more specialized functionality is needed.

The result is a flexible development model:

  • Use WebForms Core alone when its built-in capabilities are sufficient.
  • Build reusable server-side libraries on top of its API.
  • Integrate JavaScript modules when specialized client-side functionality is required.
  • Keep the server as the primary point of UI orchestration without restricting what the browser can execute.

WebForms Core does not require developers to write JavaScript, and it does not prevent them from using JavaScript. It gives developers the freedom to decide where and how each part of their application should be implemented.

Related Links

On Elanat:

On GitHub:

Top comments (0)