SwapController

The base class that powers standard HTMX features in your application.

Overview

SwapController is the core base class for your MVC controllers. It replaces the standard Controller class and adds HTMX-aware helper methods.

Note: If you prefer composition or Minimal APIs, you can use the Swap.Htmx.Extensions package instead of inheritance.


Core Features

1. SwapView()

Intelligent view rendering that adapts to the request type.

  • Browser Request: Returns View() (Full page with _Layout).
  • HTMX Request: Returns PartialView() (Content only).
public IActionResult Index()
{
    var model = _repo.GetData();
    return SwapView(model); // Handles both scenarios automatically
}

2. SwapResponse()

A fluent builder for constructing complex HTMX responses (multi-target updates, triggers, toasts).

[HttpPost]
public IActionResult Save(Note note)
{
    _repo.Save(note);
    
    return SwapResponse()
        .WithView("_NoteList", _repo.GetAll())      // Update main list
        .AlsoUpdate(SwapElements.Count, "_Count")   // Update counter
        .WithSuccessToast("Saved!")                 // Show notification
        .Build();
}

3. SwapEvent()

Trigger an event chain defined in your configuration or distributed handlers.

// Fire and forget - lets handlers decide what ID to update
return SwapEvent(new NoteCreatedEvent(note.Id))
    .WithSuccessToast("Created")
    .Build();

Sharp Edges

While convenient, SwapController has some "Sharp Edges" to be aware of.

SwapRedirectToAction vs RedirectToAction

  • RedirectToAction: Sends a 302 Found response. The browser makes a new GET request.
  • SwapRedirectToAction (Obsolete): Was an attempt to forward internally. Avoid usage.

Best Practice: If you need to redirect after a POST (Post-Redirect-Get), use a standard RedirectToAction. HTMX will respect the 302 and fetch the new page.

If you just want to update the UI without a full reload, use SwapView or SwapResponse.