DEV Community

Vikrant Bagal
Vikrant Bagal

Posted on

Escape the SPA Trap: Adding Interactivity to ASP.NET Razor Pages with HTMX

.NET without the 'JavaScript tax'

If you’ve been in the .NET ecosystem for a while, you’ve likely felt the pressure to "SPA-ify" everything. We moved from Razor Views to React, then to Blazor, and now we’re circling back. Why? Because for many data-driven business applications, the complexity of a full client-side framework is overkill.

Enter HTMX. It’s not a new framework; it’s a different way of thinking. By leveraging standard HTML attributes, you can add AJAX, CSS Transitions, WebSockets, and Server-Sent Events directly into your markup.

Why Razor Pages + HTMX?

Razor Pages are already a fantastic way to organize your .NET web apps. They use a PageModel to handle logic and a .cshtml file for rendering. When you add HTMX, you get:

  • No Build Step: No more npm install, webpack, or vite configurations for your main UI.
  • Type Safety: Your server-side C# code remains the source of truth.
  • Simplicity: You’re just returning HTML fragments instead of JSON that you then have to parse and render in the client.

A Quick Example

Imagine a simple "Add to Cart" button. In a traditional SPA, this involves a fetch call, updating a local state store, and re-rendering a component. With HTMX and Razor Pages:

<!-- In your .cshtml file -->
<button hx-post="/cart/add" 
        hx-target="#cart-count" 
        hx-swap="innerHTML">
    Add to Cart
</button>

<div id="cart-count">@Model.CartCount</div>
Enter fullscreen mode Exit fullscreen mode

In your PageModel:

public IActionResult OnPostAdd(int productId)
{
    // Logic to add to cart
    _cartService.Add(productId);

    // Return just the updated fragment
    return Partial("_CartCountPartial", _cartService.Count);
}
Enter fullscreen mode Exit fullscreen mode

The "Server-First" Renaissance

This isn't just about saving a few lines of code. It's about the Server-First movement. By keeping the UI logic closer to the data, we reduce the "context switching" between frontend and backend developers.

For teams that are already strong in C#, this approach allows you to deliver modern, snappy user experiences without hiring a dedicated JavaScript engineer or fighting with React's hydration errors.

Getting Started

  1. Add the HTMX script to your _Layout.cshtml.
  2. Start replacing your Ajax.BeginForm or jQuery calls with hx-post and hx-get.
  3. Return PartialViewResult from your PageModel handlers.

Are you ready to drop the "JavaScript tax" and get back to building features? Let me know in the comments if you’re giving HTMX a try in your next .NET project!

Top comments (0)