Search code examples
asp.net-corerazorblazorrazor-pagesblazor-server-side

Can Blazor component interaction occur inside a Razor page form without causing a HTTP POST?


I have a requirement to create a form that accepts the following (hugely simplified) data model:

public class MyPost {
    public string MyTitle { get; set; }
    public List<DateTime> Dates { get; set; } = new();
}

The challenge is that there can be many dates, and the user needs to generate them based on certain criteria (e.g. a "one-off date", or generate dates running "every Wednesday until 30th December", or any combination). Therefore I need functionality within the form to allow the user to generate/view the dates before the form is finally submitted.

I'm new to .Net Core so please excuse my ignorance as I'm suffering tutorial overload.

Problem summary

Hoping to use Blazor instead of JavaScript because of the neat date functionality in C#, I created a Blazor component to do this but any interaction (e.g. @onclick) triggers a HTTP Post in the parent Razor page which breaks everything.

Is it possible therefore to interact with a Blazor component inside a Razor page form without triggering a form POST?

Example/research

Taking Microsoft's example of the counter component and simplifying it:

<p>Count: @currentCount</p>
<button @onclick="IncrementCount">Click me</button>
@code {
    private int currentCount = 0;
    private void IncrementCount()
    {
        currentCount++;
    }
}

If this is then placed in a Razor (cshtml) page both inside and outside of a <form> tag I see totally different outcomes when interaction occurs.

<h3>Outside form tag</h3>
<Counter  />
<form method="post">
    <h3>Inside form tag</h3>
    <Counter />
</form>
  • The component outside the form tag increments and I also see no network traffic in the analyzer (although I suspect SignalR may be the reason?).
  • The component inside the form however triggers a page post when the @onclick event occurs.

enter image description here

Is it possible to use a component to create a dynamic Razor pages form, or does the entire form need to be moved within the component (the latter is a lot of work currently, hence the reason for this question before I do anything unnecessary)?


Solution

  • The issue here is that button inside forms are handled as type="submit". You should add type="button" to your actual button then it should work without a POST request.

    <p>Count: @currentCount</p>
    <button type="button" @onclick="IncrementCount">Click me</button>
    @code {
        private int currentCount = 0;
        private void IncrementCount()
        {
            currentCount++;
        }
    }