### Hyperscript Variable Commands
Source: https://aspnet-htmx.com/appendix/hyperscript-quick-guide
Examples of using `set` and `get` commands for variables and properties.
```html
0
```
--------------------------------
### Hyperscript Installation
Source: https://aspnet-htmx.com/appendix/hyperscript-quick-guide
Include the Hyperscript library via a script tag.
```html
```
--------------------------------
### Hyperscript Timing Commands
Source: https://aspnet-htmx.com/appendix/hyperscript-quick-guide
Examples of using `wait` and `settle` for timing actions.
```html
Content
```
--------------------------------
### Custom Events
Source: https://aspnet-htmx.com/appendix/hyperscript-quick-guide
Examples of listening for custom events and htmx events.
```html
Modal Content
```
--------------------------------
### Hyperscript JavaScript Integration
Source: https://aspnet-htmx.com/appendix/hyperscript-quick-guide
Examples of using `call` and `js` to execute JavaScript.
```html
```
--------------------------------
### Hyperscript Event Commands
Source: https://aspnet-htmx.com/appendix/hyperscript-quick-guide
Examples of using `trigger` and `send` to manage events.
```html
```
--------------------------------
### New Project Setup
Source: https://aspnet-htmx.com/appendix/valuable-tools-and-resource
Commands to create a new ASP.NET Core project, add necessary packages (EF Core, Htmx), and install client libraries using LibMan.
```bash
# Create project
dotnet new webapp -n MyHtmxApp
cd MyHtmxApp
# Add packages
dotnet add package Microsoft.EntityFrameworkCore.Sqlite
dotnet add package Htmx
# Add client libraries
dotnet tool install -g Microsoft.Web.LibraryManager.Cli
libman init
libman install htmx.org@1.9.10 -d wwwroot/lib/htmx
libman install hyperscript.org@0.9.12 -d wwwroot/lib/hyperscript
# Run with hot reload
dotnet watch
```
--------------------------------
### Keyboard: Global Shortcuts
Source: https://aspnet-htmx.com/appendix/hyperscript-quick-guide
Example of a global keyboard shortcut to focus a search input.
```html
```
--------------------------------
### Hyperscript Visibility Commands
Source: https://aspnet-htmx.com/appendix/hyperscript-quick-guide
Examples of using `show`, `hide`, and `toggle` commands for element visibility.
```html
```
--------------------------------
### Verify .NET SDK Installation
Source: https://aspnet-htmx.com/chapter02
Command to verify the installation of the .NET SDK.
```bash
dotnet --version
```
--------------------------------
### Hyperscript Class Commands
Source: https://aspnet-htmx.com/appendix/hyperscript-quick-guide
Examples of using `add`, `remove`, and `toggle` commands for CSS classes.
```html
```
--------------------------------
### Hyperscript Targeting Elements
Source: https://aspnet-htmx.com/appendix/hyperscript-quick-guide
Examples of targeting different elements using Hyperscript selectors.
```html
```
--------------------------------
### Project Structure Example
Source: https://aspnet-htmx.com/chapter02
An example of a well-organized ASP.NET Core Razor Pages project structure.
```text
MyHtmxApp/
|-- Pages/
| |-- Shared/
| |-- _Layout.cshtml
| |-- Partials/
| |-- Index.cshtml
| |-- Index.cshtml.cs
|-- wwwroot/
|-- appsettings.json
```
--------------------------------
### Hyperscript Attribute Commands
Source: https://aspnet-htmx.com/appendix/hyperscript-quick-guide
Examples of using `set` and `remove` commands for HTML attributes.
```html
```
--------------------------------
### head-support Configuration Example
Source: https://aspnet-htmx.com/appendix/htmx-extensions
Example of configuring head-support merge mode.
```html
```
--------------------------------
### Out-of-Band (OOB) Swap Example
Source: https://aspnet-htmx.com/appendix/htmx-command-reference
Example showing how to perform out-of-band swaps using hx-swap-oob.
```html
Main content here
Updated stats: 42 items
Operation successful!
```
--------------------------------
### Minimize Response Size - Avoid Example
Source: https://aspnet-htmx.com/chapter04
Example of returning an entire page when only a fragment is needed, which is inefficient.
```csharp
public IActionResult OnGetItem(int id)
{
var item = _service.GetById(id);
ViewData["Item"] = item;
return Page(); // Returns entire page
}
```
--------------------------------
### Hyperscript Basic Event Handling
Source: https://aspnet-htmx.com/appendix/hyperscript-quick-guide
Examples of handling common events like clicks, mouse events, keyboard input, and form submissions.
```html
Hover Me
```
--------------------------------
### multi-swap Server Response Example
Source: https://aspnet-htmx.com/appendix/htmx-extensions
Example server response for multi-swap.
```html
New header content
New main content
```
--------------------------------
### Loading Extensions from CDN and npm
Source: https://aspnet-htmx.com/appendix/htmx-extensions
Examples of how to load htmx extensions using CDNs like unpkg and cdnjs, and how to install them via npm.
```html
```
```bash
# npm installation
npm install htmx.org
```
--------------------------------
### Swap Modifiers Examples
Source: https://aspnet-htmx.com/appendix/htmx-command-reference
Examples demonstrating various swap modifiers like delay, scrolling, and transitions.
```html
```
--------------------------------
### hx-select-oob Example
Source: https://aspnet-htmx.com/appendix/htmx-command-reference
Example of using hx-select-oob to select elements for out-of-band swaps.
```html
```
--------------------------------
### hx-select Example
Source: https://aspnet-htmx.com/appendix/htmx-command-reference
Example of using hx-select to specify which part of the response to swap.
```html
```
--------------------------------
### Minimize Response Size - Good Example
Source: https://aspnet-htmx.com/chapter04
Example of returning only the necessary HTML fragment for a partial update using PartialView.
```csharp
public IActionResult OnGetItem(int id)
{
var item = _service.GetById(id);
return Partial("_Item", item);
}
```
--------------------------------
### Multiple Triggers Example
Source: https://aspnet-htmx.com/appendix/htmx-command-reference
Example showing how to specify multiple triggers for a single request, separated by commas.
```html
```
--------------------------------
### loading-states Complete Form Example
Source: https://aspnet-htmx.com/appendix/htmx-extensions
A comprehensive example demonstrating various loading-states attributes on a form.
```html
```
--------------------------------
### OOB Swap Modes Examples
Source: https://aspnet-htmx.com/chapter07
Examples demonstrating different OOB swap modes like replace, append, prepend, and innerHTML.
```html
New sidebar content
New activity entry
New alert!
Updated status
```
--------------------------------
### Caching GET Responses
Source: https://aspnet-htmx.com/chapter05
Example of setting Cache-Control headers to cache GET responses on the server.
```csharp
public IActionResult OnGetCategories()
{
Response.Headers.Append("Cache-Control", "public, max-age=300");
var categories = _categoryService.GetAll();
return Partial("_CategoryList", categories);
}
```
--------------------------------
### Basic htmx GET request example
Source: https://aspnet-htmx.com/chapter03
A button that triggers an AJAX GET request and updates a target div with the response.
```html
```
--------------------------------
### Initialize Git Repository
Source: https://aspnet-htmx.com/chapter02
Commands to initialize a Git repository and make the initial commit.
```bash
git init
git add .
git commit -m "Initial commit with htmx setup"
```
--------------------------------
### Rename Button Example
Source: https://aspnet-htmx.com/chapter14
An example of a button that uses hx-prompt to get user input for renaming an item inline.
```html
@item.Name
```
--------------------------------
### Video Player Example with hx-preserve
Source: https://aspnet-htmx.com/chapter15
Example demonstrating how hx-preserve prevents a video player from being replaced during an htmx swap.
```html
@Model.Title
@Model.Description
```
--------------------------------
### head-support ASP.NET Core Partial Example
Source: https://aspnet-htmx.com/appendix/htmx-extensions
Example of an ASP.NET Core partial view using head-support.
```cshtml
// _ArtistsPage.cshtml
@{
ViewData["Title"] = "Artists";
}
@ViewData["Title"] - Chinook Dashboard
@* Page content *@
```
--------------------------------
### Multiple OOB Updates Example
Source: https://aspnet-htmx.com/chapter07
An example showing a single response with multiple OOB updates, including updating counts, appending to logs, and replacing elements.
```html
Order #123
Shipped
4
Updated just now
Order #123 marked as shipped
```
--------------------------------
### Serve htmx locally
Source: https://aspnet-htmx.com/chapter03
Alternatively, download htmx and serve it locally from your project's wwwroot/js folder.
```html
```
--------------------------------
### Product Grid Partial Example
Source: https://aspnet-htmx.com/chapter10
A partial view for rendering a grid of products, including pagination controls.
```cshtml
@model ProductsModel
@foreach (var product in Model.Products)
{
@product.Name
@product.Price.ToString("C")
}
@if (Model.TotalPages > 1)
{
}
```
--------------------------------
### Event Modifiers
Source: https://aspnet-htmx.com/appendix/hyperscript-quick-guide
Examples of using event modifiers like 'once', 'debounced', and 'throttled'.
```html
```
--------------------------------
### OOB Swap Strategies Examples
Source: https://aspnet-htmx.com/chapter16
Illustrates different swap strategies available for out-of-band updates.
```html
55
New message!
```
--------------------------------
### Make script executable and run
Source: https://aspnet-htmx.com/chapter23
Commands to make the infrastructure setup script executable and then run it.
```bash
chmod +x infrastructure/azure-setup.sh
./infrastructure/azure-setup.sh
```
--------------------------------
### htmx Button Interaction Example
Source: https://aspnet-htmx.com/chapter01
A simple example demonstrating how a button click can trigger an HTTP GET request using htmx attributes and update a specific part of the DOM.
```html
```
--------------------------------
### Debounced Search
Source: https://aspnet-htmx.com/appendix/htmx-command-reference
An example of a debounced search input that triggers a GET request after a delay.
```html
```
--------------------------------
### Abort Strategy Example
Source: https://aspnet-htmx.com/chapter19
Cancels the in-flight request and starts the new one.
```html
```
--------------------------------
### Using hx-select-oob for OOB Control
Source: https://aspnet-htmx.com/chapter07
An example demonstrating how to use the `hx-select-oob` attribute to specify which parts of the response should be treated as OOB updates.
```html
```
--------------------------------
### Event Filtering
Source: https://aspnet-htmx.com/appendix/hyperscript-quick-guide
Examples of filtering events based on key presses, target elements, and compound conditions.
```html
Click backdrop to close
```
--------------------------------
### Server sends HTML that gets swapped
Source: https://aspnet-htmx.com/appendix/htmx-extensions
Example of how the server can send HTML to be swapped into the DOM.
```html
Hello from server!
```
--------------------------------
### Get Azure Advisor Recommendations
Source: https://aspnet-htmx.com/chapter23
Azure CLI command to list cost-related recommendations from Azure Advisor for a specific resource group.
```bash
# Get Azure Advisor recommendations
az advisor recommendation list \
--resource-group chinook-rg \
--category cost
```
--------------------------------
### Create and Run a New Razor Pages Project
Source: https://aspnet-htmx.com/chapter02
Commands to create a new ASP.NET Core Razor Pages project and run it.
```bash
dotnet new razor -o MyHtmxApp
cd MyHtmxApp
dotnet run
```
--------------------------------
### hx-get Example
Source: https://aspnet-htmx.com/appendix/htmx-command-reference
Issues an HTTP GET request to the specified URL and targets an element to update with the response.
```html
```
```csharp
// Razor Pages handler
public IActionResult OnGetList()
{
var artists = _artistService.GetAll();
return Partial("_ArtistList", artists);
}
```
--------------------------------
### Complete Working Example - Index.cshtml
Source: https://aspnet-htmx.com/chapter03
The main Razor Page (.cshtml) demonstrating dynamic content loading, live search, and form submission using htmx attributes.
```cshtml
@page
@model IndexModel
htmx Demo
Dynamic Content Loading
Live Search
Form Submission
```
--------------------------------
### Client-Side Templates Installation
Source: https://aspnet-htmx.com/appendix/htmx-extensions
Includes the HTMX client-side-templates extension and a template engine library (Mustache example).
```html
```
--------------------------------
### Passing Parameters with hx-vals
Source: https://aspnet-htmx.com/chapter05
An example of using hx-vals to send additional JSON-formatted parameters (category and inStock) with a GET request.
```html
```
--------------------------------
### Using hx-boost for simpler navigation
Source: https://aspnet-htmx.com/chapter10
An example demonstrating how to use the `hx-boost="true"` attribute on a container to make all its links and forms behave like HTMX requests.
```html
```
--------------------------------
### Screen Reader Feedback Example
Source: https://aspnet-htmx.com/chapter16
This example demonstrates how to provide screen reader feedback for important updates by including screen-reader-only text within an OOB swapped element.
```html
Success:
Item added to cart!
```
--------------------------------
### Verify Element Receives Event (Incorrect)
Source: https://aspnet-htmx.com/chapter21
Example showing an incorrect setup where Hyperscript on an unrelated element will not receive the htmx event because events bubble up from the target element.
```html
Load Content
```
--------------------------------
### Opening the Modal with HTMX
Source: https://aspnet-htmx.com/chapter11
An example of a button that triggers an HTMX GET request to load content into the modal and then opens the modal using HTMX attributes and Hyperscript.
```html
```
--------------------------------
### Azure CDN Setup Script
Source: https://aspnet-htmx.com/chapter23
Shell script for setting up Azure CDN.
```bash
#!/bin/bash
```
--------------------------------
### Complete Working Example - Index.cshtml.cs
Source: https://aspnet-htmx.com/chapter03
The server-side code-behind file (.cshtml.cs) for the Razor Page, containing handlers for fetching quotes, searching fruits, and greeting users.
```csharp
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
public class IndexModel : PageModel
{
private static readonly string[] Quotes =
{
"The best code is no code at all.",
"Simplicity is the ultimate sophistication.",
"First, solve the problem. Then, write the code.",
"Code is like humor. When you have to explain it, it is bad."
};
private static readonly string[] Fruits =
{
"Apple", "Apricot", "Banana", "Blueberry", "Cherry",
"Grape", "Lemon", "Mango", "Orange", "Peach", "Pear",
"Pineapple", "Raspberry", "Strawberry", "Watermelon"
};
public void OnGet()
{
}
public IActionResult OnGetQuote()
{
var quote = Quotes[Random.Shared.Next(Quotes.Length)];
return Content($"
{quote}
", "text/html");
}
public IActionResult OnGetSearch(string query)
{
if (string.IsNullOrWhiteSpace(query))
{
return Content("", "text/html");
}
var matches = Fruits
.Where(f => f.Contains(query, StringComparison.OrdinalIgnoreCase))
.ToList();
if (matches.Count == 0)
{
return Content("
No matches found
", "text/html");
}
var html = string.Join("", matches.Select(f => $"
{f}
"));
return Content(html, "text/html");
}
public IActionResult OnPostGreet(string name)
{
if (string.IsNullOrWhiteSpace(name))
{
return Content("
Please enter your name.
", "text/html");
}
return Content($"
Hello, {name}! Welcome to htmx.
", "text/html");
}
}
```
--------------------------------
### Product Results Element with History Caching Attributes
Source: https://aspnet-htmx.com/chapter18
This example shows an element that triggers a GET request for product data, enables history caching, targets itself for updates, and selects a specific part of the response to cache.
```html
```
--------------------------------
### OOB Update Example
Source: https://aspnet-htmx.com/chapter21
Example of an OOB update element in a server response.
```html
275
```
--------------------------------
### Live Search - C#
Source: https://aspnet-htmx.com/chapter07
C# handler for processing live search queries.
```csharp
public IActionResult OnGetResults(string query)
{
if (string.IsNullOrWhiteSpace(query))
{
return Content("", "text/html");
}
var results = _searchService.Search(query);
return Partial("_SearchResults", results);
}
```
--------------------------------
### alpine-morph Usage Example
Source: https://aspnet-htmx.com/appendix/htmx-extensions
Example of combining htmx and Alpine.js with alpine-morph.
```html
```
--------------------------------
### Azure Resource Setup
Source: https://aspnet-htmx.com/chapter23
Azure CLI commands to set up the necessary resources for data protection in a production environment, including storage accounts, containers, and Key Vault keys, and granting necessary permissions.
```bash
# Create storage account for data protection keys
az storage account create \
--name chinookstorage \
--resource-group chinook-rg \
--location eastus \
--sku Standard_LRS
# Create container
az storage container create \
--name data-protection-keys \
--account-name chinookstorage \
--auth-mode login
# Create Key Vault key for encryption
az keyvault key create \
--vault-name chinook-vault \
--name DataProtectionKey \
--protection software
# Grant Web App access to storage
WEBAPP_IDENTITY=$(az webapp identity show --name chinook-dashboard --resource-group chinook-rg --query principalId -o tsv)
az role assignment create \
--assignee $WEBAPP_IDENTITY \
--role "Storage Blob Data Contributor" \
--scope "/subscriptions/{sub}/resourceGroups/chinook-rg/providers/Microsoft.Storage/storageAccounts/chinookstorage"
# Grant access to Key Vault key
az keyvault set-policy \
--name chinook-vault \
--object-id $WEBAPP_IDENTITY \
--key-permissions get unwrapKey wrapKey
```
--------------------------------
### Configuration in Program.cs
Source: https://aspnet-htmx.com/chapter23
Example of how to configure and use the HtmxResponseCachingMiddleware in Program.cs.
```csharp
// Configure htmx caching profiles
builder.Services.AddHtmxResponseCaching(options =>
{
options.VaryByHxRequest = true;
options.DefaultMaxAge = 0;
// Cache genre list for 1 hour
options.Profiles["/artists:genrelist"] = new CacheProfile
{
MaxAge = 3600,
IsPrivate = false
};
// Cache navigation for 5 minutes
options.Profiles["/shared:navigation"] = new CacheProfile
{
MaxAge = 300,
IsPrivate = false
};
// Don't cache search results
options.Profiles["/artists:list"] = new CacheProfile
{
NoStore = true
};
});
// In middleware pipeline (after routing, before endpoints)
app.UseHtmxResponseCaching();
```
--------------------------------
### Complete hx-select Example
Source: https://aspnet-htmx.com/chapter16
Demonstrates how hx-select can be used to extract specific content from a server response.
```cshtml
@page
@model ArticlesModel
Articles
Loading article...
Select an article to read.
```
```csharp
public class ArticlesModel : PageModel
{
private readonly IArticleService _articleService;
public ArticlesModel(IArticleService articleService)
{
_articleService = articleService;
}
public List Articles { get; set; } = new();
public void OnGet()
{
Articles = _articleService.GetAll();
}
public IActionResult OnGet(string slug)
{
var article = _articleService.GetBySlug(slug);
if (article == null) return NotFound();
// Return full page for direct navigation, partial for htmx
if (Request.Headers.ContainsKey("HX-Request"))
{
return Partial("_ArticleFull", article);
}
return Page();
}
}
```
```cshtml
@model Article
@Model.Title
By @Model.Author on @Model.PublishedAt.ToString("MMMM d, yyyy")
@Html.Raw(Model.HtmlContent)
```
--------------------------------
### hx-history-elt Example
Source: https://aspnet-htmx.com/chapter10
Example of adding the 'hx-history-elt' attribute to a container for proper history management.
```html
```
--------------------------------
### Install Playwright Browsers
Source: https://aspnet-htmx.com/chapter22
Command to install Playwright browsers from the test project directory.
```powershell
# Run from the test project directory
pwsh bin/Debug/net8.0/playwright.ps1 install
```
--------------------------------
### hx-swap Examples
Source: https://aspnet-htmx.com/appendix/htmx-command-reference
Illustrates different methods for swapping response content into the target element.
```html
```
--------------------------------
### Managing Secrets - Do this
Source: https://aspnet-htmx.com/chapter23
Example of how to use a placeholder for connection strings in appsettings.Production.json, which will be overridden by Azure.
```json
"ConnectionStrings": {
"ChinookConnection": "SET_IN_AZURE_APP_SETTINGS"
}
```
--------------------------------
### multi-swap Usage Example
Source: https://aspnet-htmx.com/appendix/htmx-extensions
Example of swapping multiple elements using multi-swap.
```html
```
--------------------------------
### head-support Usage Example
Source: https://aspnet-htmx.com/appendix/htmx-extensions
Example of a server response with head elements to be merged.
```html
Artists - Chinook Dashboard
```
--------------------------------
### Complete Custom Domain Setup Script
Source: https://aspnet-htmx.com/chapter23
A bash script to automate the process of adding a custom domain, creating a managed SSL certificate, binding it, and enforcing HTTPS for an Azure Web App.
```bash
#!/bin/bash
# Configuration
RESOURCE_GROUP="chinook-rg"
WEB_APP_NAME="chinook-dashboard"
CUSTOM_DOMAIN="chinook.example.com"
echo "Setting up custom domain: $CUSTOM_DOMAIN"
echo "========================================="
# ============================================
# 1. Add Custom Domain
# ============================================
echo "Adding custom domain to Web App..."
echo "NOTE: Ensure DNS CNAME record exists first!"
echo " CNAME: chinook -> ${WEB_APP_NAME}.azurewebsites.net"
echo ""
read -p "DNS configured? (y/n): " DNS_READY
if [ "$DNS_READY" != "y" ]; then
echo "Please configure DNS first, then re-run this script."
exit 1
fi
az webapp config hostname add \
--webapp-name $WEB_APP_NAME \
--resource-group $RESOURCE_GROUP \
--hostname $CUSTOM_DOMAIN \
--output none
echo "✓ Custom domain added"
# ============================================
# 2. Create Managed SSL Certificate
# ============================================
echo "Creating managed SSL certificate..."
az webapp config ssl create \
--name $WEB_APP_NAME \
--resource-group $RESOURCE_GROUP \
--hostname $CUSTOM_DOMAIN \
--output none
echo "✓ SSL certificate created (may take a few minutes to provision)"
# ============================================
# 3. Bind SSL Certificate
# ============================================
echo "Binding SSL certificate to domain..."
# Get the certificate thumbprint
THUMBPRINT=$(az webapp config ssl list \
--resource-group $RESOURCE_GROUP \
--query "[?subjectName=='$CUSTOM_DOMAIN'].thumbprint" \
--output tsv)
if [ -z "$THUMBPRINT" ]; then
echo "Certificate not ready yet. Check Azure Portal in a few minutes."
else
az webapp config ssl bind \
--name $WEB_APP_NAME \
--resource-group $RESOURCE_GROUP \
--certificate-thumbprint $THUMBPRINT \
--ssl-type SNI \
--output none
echo "✓ SSL certificate bound"
fi
# ============================================
# 4. Enforce HTTPS
# ============================================
echo "Enforcing HTTPS redirect..."
az webapp update \
--name $WEB_APP_NAME \
--resource-group $RESOURCE_GROUP \
--https-only true \
--output none
echo "✓ HTTPS-only mode enabled"
# ============================================
# Summary
# ============================================
echo ""
echo "========================================"
echo "Custom Domain Setup Complete!"
echo "========================================"
echo ""
echo "Your site is now available at:"
echo " https://$CUSTOM_DOMAIN"
echo ""
echo "Note: SSL certificate provisioning may take up to 15 minutes."
echo "Check the Azure Portal if the certificate doesn't appear immediately."
```