Matias Masso
Matias Masso

Reputation: 1980

How to navigate posting form data to external url in Blazor Server Side?

I'm working on an e-commerce which has to redirect to an external payment gateway while posting form data.
A trivial process in Html5 but I wonder how may we manage this on a blazored way.

<form action="https://externalUrl.com" method="post">
  <input type="number" name="amount">
  <input type="submit" value="Submit">
</form>

Upvotes: 0

Views: 1360

Answers (1)

Marius
Marius

Reputation: 1574

You can do this using EditForm. But keep in mind the differences between EditForm and HTML's form element.

You will need something like:

@using System.ComponentModel.DataAnnotations
@inject HttpClient HttpClient
@page "/"

<EditForm Model="postObject" OnInvalidSubmit="PostExternal">

    @*Model Parameter is the top level model and an EditContext will be created from this model. Handy for validation using Data Annotations.*@
    @*OnInvalidSubmit will be executed when the validation on the model succeeds.*@
    @*Custom validation can be done using the EditContext and OnSubmit Parameters*@

    <DataAnnotationsValidator /> @*For validation to work*@
    <ValidationSummary /> @*All validation messages*@
    <InputNumber @bind-Value="postObject.Price" /> @*These default blazor components require to be within the EditForm component*@

    <button type="submit">Submit</button>
</EditForm>

@code {
    PostObject postObject = new PostObject();

    async Task PostExternal()
    {
        HttpResponseMessage response = await HttpClient.PostAsJsonAsync<PostObject>("some.url.com", postObject);

        //Do what you need with the response object
    }

    internal class PostObject
    {
        [Range(0, 9999)]
        public decimal Price { get; set; }
    }
}

Upvotes: 0

Related Questions