I’ve been out of the FE game for a while having specialised in back-end API development in .Net around 4-5 years ago so forgive me if this is a simple one but it’s a project using Razor Pages and Htmx, both of which I am just dipping my toes into.
I’ve been following this tutorial from Jetbrains as a gentle introduction to Htmx
https://www.jetbrains.com/guide/dotnet/tutorials/htmx-aspnetcore/htmx-counter/
Unlike the tutorial, I am using .Net 8 for the backend portion.
The issue I face is for me, my counter page is returning 400 bad request when following along with the code they are demonstrating.
I have a Counter razor page which has a simple button that triggers an empty hx-post to the current page and is supposed to replace the contents of the target div with the new value from the server. Pretty straightforward. Except despite following their example to the letter, I am receiving a 400 bad request when I hit the button.
My Razor Page code is as follows:
<!-- Counter.cshtml -->
@page
@model Counter
@{
ViewData["Title"] = "Counter";
}
<div class="card p-5 mb-4">
<div class="d-flex justify-content-between">
<div>
<!-- change the button -->
<button class="btn btn-primary"
hx-post=""
hx-target="#example_one_count"
hx-vals="">
<i class="fa fa-plus-circle"></i>
Increment
</button>
</div>
<div>
<h2 id="example_one_count" class="fs-2" style="text-align: right">
<span>0</span>
</h2>
</div>
</div>
</div>
And on the backend my handlers are as follows:
<!-- Counter.cshtml.cs -->
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace HtmxWebApp.Pages;
public class Counter : PageModel
{
private static int count = 0;
public void OnGet()
{
// reset on refresh
count = 0;
}
public async Task<IActionResult> OnPostAsync()
{
// TODO: Increment the count on each request
return Content($"<span>{++count}</span>", "text/html");
}
}
I know that Htmx is included and working correctly as it’s injected into the _layout template and I can see that the previous example I ran through replacing content with a get request works absolutely fine, but I’m just not sure what gives with this.
Is it possibly a change to how post is handled in Razor Pages in .Net 8? Like I said, I’m an API developer so I only work with .Net Core Web Apis so I’m not longer familiar with the ins and outs of Razor Pages as I never need to use them
Any help with this issue would be greatly appreciated. I’m sure it’s a simple one but I’ve tried everything.