This repository demonstrates ASP.NET Core ViewComponents with HTMX for building dynamic, interactive web applications using server-side rendering and minimal JavaScript.
- ViewComponents are reusable C# classes in
ViewComponents/that render HTML fragments - Each component has a
XxxViewComponent.csclass and correspondingXxx.cshtmlview - ViewComponents are served via
ComponentControllerat/component/{name}endpoints - Components return pure HTML fragments (no layout) for HTMX to swap into the page
- Main Razor Pages (
index.cshtml,testpage.cshtml) use HTMX to dynamically load components - Components are fetched with
hx-get="/component/{name}"attributes - Supports triggers:
load(initial fetch),every Xs(polling), custom events (reactive updates)
- ViewComponents dispatch custom DOM events via
HX-Triggerresponse headers - Example:
LoginViewComponenttriggersuserLoggedIn/userLoggedOutevents - Other components listen via
hx-trigger="userLoggedIn from:body"for reactive updates - Multiple components can react to the same event simultaneously
- Login state stored in
logincookie ("true"or"false") - Set by
LoginViewComponentviaHttpContext.Response.Cookies.Append() - Read by protected components (
FavoritesViewComponent,PaidContentViewComponent)
- ViewComponents can update multiple DOM areas in one request using
hx-swap-oob="innerHTML" - See
OutOfBandViewComponentfor example of multi-target updates
dotnet watch run # Auto-reload on file changes (port 5274)Or use VS Code tasks: build, watch, or publish
Controllers/ComponentController.cs- HTTP endpoints that return ViewComponentsViewComponents/{Name}/{Name}ViewComponent.cs- Component logic (C# classes)ViewComponents/{Name}/{Name}.cshtml- Component views (Razor templates)Infrastructure/Razor/ViewComponentLocationExpander.cs- Custom view resolutionPages/Shared/_Layout.cshtml- Global HTMX + Tailwind setupPages/testpage.cshtml- Example page with HTMX-loaded componentsProgram.cs- App configuration (RazorPages + Controllers + ViewComponent location expansion)
- Server-side rendering: No large JavaScript framework needed
- Reusable components: ViewComponents are testable, type-safe C# classes
- Progressive enhancement: Pages work without JavaScript, enhanced with HTMX
- Clear separation: Controllers handle routing, ViewComponents handle rendering
- Minimal client code: HTMX handles all dynamic behavior declaratively
ViewComponents/ # Reusable UI fragments
Login/
LoginViewComponent.cs
Login.cshtml
Favorites/
FavoritesViewComponent.cs
Favorites.cshtml
Controllers/ # HTTP endpoints for components
ComponentController.cs
Pages/ # Main Razor Pages
index.cshtml
testpage.cshtml
Shared/_Layout.cshtml
Infrastructure/Razor/ # Custom view resolution
wwwroot/js/ # HTMX & Tailwind (local files)
This demo is provided as-is for educational purposes.