No series is complete without a "Hello, World" sample
What would a video series be without a "Hello, World!" example. Starting on our page, we have a button. Our goal is to click the button and change the HTML element that says "Change Me" into displaying hello world.
From the sample's HTML, The first step is to decorate our button with the HTMX attributes of
hx-get attribute requires an endpoint value that we'll make an HTTP request of
GET to. The endpoint will respond with a "Hello, World" HTML snippet. In this case, since the URL path is identical to our current page, thus we can leave the value empty.
hx-target attribute is the destination for our HTML response. By default, HTMX swaps content into our target's
innerHTML. The target attribute uses common CSS selectors to find an element. We can use the
# symbol to find elements with a particular
id. While using
id is common, you can use any valid CSS selector to perform a swap.
Finally, we need to program the behavior in our endpoint. We want the endpoint to respond with our "hello world" HTML snippet. We do this by using HTMX.NET to return a different response depending on an HTMX HTTP header. All HTMX requests set an
HX-Request header, which we can use to determine the originator of an HTTP request. Within our Razor Page instance, we can change the
OnGet method to return either a fully rendered page or an HTML fragment.
We'll get more into HTMX.NET later, but in the following example we can see one of the extension methods it provides. The
IsHtmx call is a convenience method used to determine if an incoming occurred through the HTMX client-side library.
public IActionResult OnGet()
? Content("<span>Hello, World!</span>", "text/html")
When done correctly, clicking the button will now change the target element.
Congratulations! You're on your way to building HTMX and ASP.NET Core web applications. In the following video, let's see how to create a more complex sample with server-side state management.