Reputation: 3677
In my Blazor Server-Side App, I have to call another website and submit a form. However, before the form can be submitted the app needs to do some local processing and based on the result submit the form or do not. How is this done?
My thought was to have a button that has @onclick
and from that function call the form. Something like this:
<button @onclick="MyFunction">Click Me</button>
<form METHOD="POST" ACTION="https://someURL.com">
<input TYPE="hidden" NAME="value1" VALUE="@myValue1">
<input TYPE="hidden" NAME="value2" VALUE="@myValue2">
<input TYPE="SUBMIT" NAME="SUBMIT" class="btn btn-primary" style="margin: 5px" VALUE="Do stuff">
</form>
@code{
private void MyFunction()
{
if (AmazingLogicFunction())
//Code to click SUBMIT
}
}
However, I cannot seem to be able to get the element
named SUBMIT
If I have to do it some other way I am fine with that.
Upvotes: 2
Views: 4560
Reputation: 30433
The thing to remember here is that you aren't actually submitting and reloading the whole page like you would with a traditional HTML form and a server side web technology (e.g. ASP).
In Blazor the submit button is simply calling your code where you then program some action of your choosing to occur. For example, if you then wanted to move to a different page after the action, you would then manually tell Blazor to change the page component displayed via Blazor's routing.
Using Blazor's EditForm
component makes handling forms a bit simpler. If you do that you can then do something like this (from the official documentation):
<EditForm EditContext="@editContext" OnSubmit="@HandleSubmit"> ... <button type="submit">Submit</button> </EditForm>
@code { private Starship starship = new Starship() { ProductionDate = DateTime.UtcNow }; private EditContext editContext; protected override void OnInitialized() { editContext = new EditContext(starship); } private async Task HandleSubmit() { var isValid = editContext.Validate(); if (isValid) { AmazingLogicFunction() // whatever you want to happen next } else { ... } } }
Or, if you only want your function to fire when the form data is valid, you can simplify things to:
<EditForm Model="@exampleModel" OnValidSubmit="@HandleValidSubmit"> <DataAnnotationsValidator /> <ValidationSummary /> <InputText id="name" @bind-Value="exampleModel.Name" /> <button type="submit">Submit</button> </EditForm>
@code { private ExampleModel exampleModel = new ExampleModel(); private void HandleValidSubmit() { AmazingLogicFunction() // whatever you want to happen next } }
Have a good read through the whole ASP.NET Core Blazor forms and validation section of the documentation and in particular the parts about OnValidSubmit
and OnSubmit
.
Upvotes: 4