sanepete
sanepete

Reputation: 1130

What do I have to do to post data to a .Net 9.0 Razor component?

I would like to pass a value from a Blazor web assembly component to the server and redirect to another top level Razor component, but not display the value in the address bar. The only way I've managed this is to send the value through the HttpClient to an API, save it as a session variable then redirect to the page. I would like to simply use an HTML form in the sending web assembly, with its action parameter set to the receiving page/component, action="/myawesomereceivingpage" and post the value. My current design uses a <form> tag on the web assembly component, with the attribute @formname="myawesomeform". The receiving Razor component class is decorated with [IgnoreAntiforgeryToken] and its Program.cs class with

builder.Services.AddAntiforgery(options =>
{
  options.Cookie.Expiration = TimeSpan.Zero;
});

and

app.UseAntiforgery();

Which, on submission renders the message:

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>.

Is this even fixable, or possible WITH anti forgery validation, please?

Upvotes: 0

Views: 60

Answers (1)

Ruikai Feng
Ruikai Feng

Reputation: 11896

A minimal example:

The component you send the request:

@page "/"



<form @formname="myform" @onsubmit="Submit"  action="counter" method="post">
    <input name="Name"/>
    <AntiforgeryToken/>
    <input id="send" type="submit" value="Send" />
</form>

@code{

    [SupplyParameterFromForm]
    private string? Name { get; set; }
    private void Submit()
    {

    }
    protected override void OnInitialized()
    {
        base.OnInitialized();
    }
}

the component you receive the request:

@page "/counter"


<form @formname="myform" @onsubmit="Submit"  method="post">
    
</form>
@code {
    

    

    [SupplyParameterFromForm]
    private string? Name { get; set; }
    private void Submit()
    {

    }
    protected override void OnInitialized()
    {
        base.OnInitialized();
    }
}

To make it work,there should be a form with same form name and same handler name in both components,we usually only send post request to the component it self in static rendering

Result: enter image description here

Upvotes: 0

Related Questions