Class HtmxRequestAttribute
- Namespace
- Ramstack.HtmxToolkit
- Assembly
- Ramstack.HtmxToolkit.dll
Restricts an action to HTMX requests.
[AttributeUsage(AttributeTargets.Method)]
public sealed class HtmxRequestAttribute : Attribute, IActionConstraint, IActionConstraintMetadata
- Inheritance
-
HtmxRequestAttribute
- Implements
- Inherited Members
Examples
// A widget polls this URL; it is not a page. The action is selected only
// for HTMX requests, so a direct browser visit gets 404 instead of a bare fragment.
[HtmxRequest]
[HttpGet("/orders/{id:int}/status")]
public IActionResult Status(int id) =>
PartialView("_OrderStatus", orders.GetStatus(id));
Remarks
The attribute accepts the requests for which IsHtmxRequest(HttpRequest) returns true. History restoration requests are not among them, because HTMX treats them as full page loads, so MVC selects an action without the attribute for the same route.
Properties
BoostedFilter
Gets or sets the boosted navigation filter for the action.
public HtmxBoostedFilter BoostedFilter { get; set; }
Property Value
Examples
[HtmxRequest(BoostedFilter = HtmxBoostedFilter.Boosted)]
public IActionResult Navigation() =>
PartialView("_Navigation", menu.Items);
Remarks
- Any, the default, does not restrict boosted navigation.
- Boosted accepts only boosted HTMX requests.
- NonBoosted accepts only non-boosted HTMX requests.
Order
The constraint order.
public int Order { get; }
Property Value
Remarks
Constraints are grouped into stages by the value of Order. See remarks on IActionConstraint.
RequestType
Gets or sets the type of HTMX request accepted by the action.
public HtmxRequestType RequestType { get; set; }
Property Value
Examples
[HttpGet("/profile")]
public IActionResult Profile() =>
View();
[HttpGet("/profile")]
[HtmxRequest(RequestType = HtmxRequestType.Partial)]
public IActionResult ProfileFragment() =>
PartialView("_Profile");
Remarks
The default, Unspecified, does not restrict the request type. Other values require a matching RequestType. When BoostedFilter is also set, both conditions must be satisfied.
HTMX 4.x sends the HX-Request-Type header itself; for HTMX 1.9.x and 2.x,
the Toolkit script (htmx-toolkit.js) adds it.
Methods
Accept(ActionConstraintContext)
Determines whether an action is a valid candidate for selection.
public bool Accept(ActionConstraintContext context)
Parameters
contextActionConstraintContext
Returns
- bool
True if the action is valid for selection, otherwise false.