Quantcast
Channel: Active questions tagged blazor - Stack Overflow
Viewing all articles
Browse latest Browse all 4285

When trying to submit a form to an API endpoint I get a POST error

$
0
0

So I'm trying to submit a form from a .razor page to an endpoint I've made in a controller, but when I do I get returned a very odd error that despite my best efforts to understand Blazor routing, isn't being fixed.

The error I get specifically is The POST request does not specify which form is being submitted. To fix this, ensure <form> elements have a @formname attribute with any unique value, or pass a FormName parameter if using <EditForm>.

My .razor page code looks like

@rendermode InteractiveServer@inject HttpClient Http<EditForm @formname="myForm" Model="formData" OnValidSubmit="HandleValidSubmit"><InputText @bind-Value="formData.Text" class="form-control" /><button type="submit" class="btn btn-primary">Submit</button></EditForm>@if (!string.IsNullOrEmpty(message)){<p>@message</p>}@code {    private FormData formData = new();    private string? message;    private async Task HandleValidSubmit()    {        var response = await Http.PostAsJsonAsync("/api/command", formData);        message = response.IsSuccessStatusCode ? "Success!" : "Failure.";    }    public class FormData    {        public string Text { get; set; } = string.Empty;    }}

And the controller method is written like so:

using Microsoft.AspNetCore.Mvc;[ApiController][Route("api/[controller]")]public class TestController : ControllerBase{    [HttpPost]    public IActionResult PostCommand([FromBody] CommandData data)    {        // Do something with the data        return Ok(new { status = "received", receivedText = data.Text });    }    public class CommandData    {        public string Text { get; set; } = string.Empty;    }}

I'm using Blazor Server, not WebAssembly.

I've tried all the conventional fixes, I replaced "OnSubmit" with "OnValidSubmit" to prevent the form from being sent separately to my controller call, I gave my form the formname parameter, etc.


Viewing all articles
Browse latest Browse all 4285