Core Feature
SwapView
One view, two behaviors. Full pages for browsers, partials for HTMX.
The Problem
In a typical HTMX app, you need to create two versions of every page: one with the layout (for browser navigation) and one without (for HTMX requests).
Or worse, you end up with brittle conditionals everywhere:
❌ The old way
if (Request.Headers["HX-Request"].Any())
return PartialView(model);
else
return View(model);
The Solution
SwapView() detects the request type automatically.
Write your view once—it works for both scenarios.
✅ The Swap.Htmx way
public IActionResult Index()
{
var products = _repo.GetAll();
return SwapView(products); // Just works™
}
How It Works
- Browser Navigation: Returns
View()with your_Layout.cshtmlapplied. - HTMX Request: Returns
PartialView()with no layout, perfect for swapping into the page. - Cache Headers: Automatically adds
Vary: HX-Requestso browsers cache correctly.
View Name Resolution
SwapView follows standard MVC conventions:
Uses Views/Products/Index.cshtml
return SwapView();
Uses Views/Products/List.cshtml
return SwapView("List", products);
Uses Views/Shared/_ProductCard.cshtml
return SwapView("_ProductCard", product);
Quick Facts
- ✓ Zero configuration required
- ✓ Works with all view engines
- ✓ Compatible with caching