Table of Contents

Class HttpResponseExtensions

Namespace
Ramstack.HtmxToolkit
Assembly
Ramstack.HtmxToolkit.dll

Provides extension methods for the HttpResponse class.

public static class HttpResponseExtensions
Inheritance
HttpResponseExtensions
Inherited Members

Methods

GetHtmxHeaders(HttpResponse)

Returns a strongly typed view of the HTMX response headers.

public static HtmxResponseHeaders GetHtmxHeaders(this HttpResponse response)

Parameters

response HttpResponse

The HTTP response.

Returns

HtmxResponseHeaders

The HtmxResponseHeaders.

Examples

// Sends invalid HTMX form posts to a shared error area,
// unless the action has already chosen another target.
public sealed class HtmxValidationTargetFilter : IResultFilter
{
    public void OnResultExecuting(ResultExecutingContext context)
    {
        var http = context.HttpContext;
        if (context.ModelState.IsValid || !http.Request.IsHtmxRequest())
            return;

        var htmx = http.Response.GetHtmxHeaders();
        htmx.Retarget ??= "#form-errors";
    }

    public void OnResultExecuted(ResultExecutedContext context)
    {
    }
}

Htmx(HttpResponse, Action<HtmxResponse>)

Configures the HTMX response headers when the current request is an HTMX request.

public static void Htmx(this HttpResponse response, Action<HtmxResponse> configure)

Parameters

response HttpResponse

The HTTP response to configure.

configure Action<HtmxResponse>

The delegate that configures the HTMX response headers.

Examples

public IActionResult OnGetProduct(string sku)
{
    var product = catalog.Find(sku);
    if (product is null)
    {
        // Runs only for HTMX requests: show the message in the notice area
        // instead of the product panel that the button targets.
        Response.Htmx(htmx => htmx.Retarget("#product-notice"));
        return Partial("_ProductNotFound", sku);
    }

    return Partial("_ProductDetails", product);
}

Htmx<TState>(HttpResponse, Action<HtmxResponse, TState>, TState)

Configures the HTMX response headers when the current request is an HTMX request.

public static void Htmx<TState>(this HttpResponse response, Action<HtmxResponse, TState> configure, TState state)

Parameters

response HttpResponse

The HTTP response to configure.

configure Action<HtmxResponse, TState>

The delegate that configures the HTMX response headers using state.

state TState

The state passed to configure.

Type Parameters

TState

Examples

var url = Url.Action(nameof(Show), new { id = product.Id })!;

// The static lambda captures nothing: the URL is passed as state,
// so the call does not allocate a closure.
Response.Htmx(static (htmx, url) => htmx.PushUrl(url), url);