Created
October 17, 2023 19:31
-
-
Save chrcar01/307c08711558babf16c0d9411f35b9c6 to your computer and use it in GitHub Desktop.
Htmx + ASP.NET(.NET 8 RC2) -> Minimal Api Hello World Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
ASP.NET MinimalApi, Htmx Demo | |
Notes: | |
* only tested with .NET 8 RC2 | |
* don't do something like this in production, this is just a dumbed down example of how to use Htmx with ASP.NET | |
1) Create a new web api project: | |
dotnet new webapi --no-https -n HtmxMinApiDemo | |
2) Replace the entire contents of the generated Program.cs file with all of this content | |
3) Run the project: | |
dotnet run | |
4) Navigate to, http://localhost:8989, click the button then click the text, it just toggles back and forth | |
*/ | |
// Html fragment containing the hello world H1 element | |
const string HTML_HELLO_WORLD = """<h1 hx-get="/button" hx-swap="outerHTML" style="cursor:pointer">Hello World!</h1>"""; | |
// Html fragment containing the button element | |
const string HTML_BUTTON = """<button hx-get="/hello-world" hx-swap="outerHTML">Click Me</button>"""; | |
// Initial Html page containing the button fragment | |
const string HTML_PAGE_SHELL = $""" | |
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<title>HtmxMinimalApiDemo</title> | |
</head> | |
<body> | |
{HTML_BUTTON} | |
<script src="https://unpkg.com/htmx.org@1.9.6"></script> | |
</body> | |
</html> | |
"""; | |
var builder = WebApplication.CreateBuilder(); | |
var app = builder.Build(); | |
app.MapGet("/", () => Results.Content(HTML_PAGE_SHELL, "text/html")); | |
app.MapGet("/hello-world", () => Results.Content(HTML_HELLO_WORLD, "text/html")); | |
app.MapGet("/button", () => Results.Content(HTML_BUTTON, "text/html")); | |
app.Run("http://localhost:8989"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment