I'm new to Blazor and I'm trying to build a very simple form with it. The method OnInitialized
works fine, meaning after rendering the page the value "Hello World!" is shown in the text box.
However, if I change the value and submit the form the value does update the field userInput
. Does anybody know the reason for it and how to fix it?
Cheers!
@page "/simpleform"
<PageTitle>TestPage</PageTitle>
<h3>Einfaches Formular</h3>
<EditForm Model="userInput" OnValidSubmit="HandleSubmit" FormName="test">
<DataAnnotationsValidator />
<ValidationSummary />
<div class="form-group">
<label for="inputText">Text eingeben</label>
<InputText id="inputText" class="form-control" @bind-Value="userInput.InputText" />
</div>
<button type="submit" class="btn btn-primary">Absenden</button>
</EditForm>
@if (submittedText != null)
{
<p>Du hast eingegeben: @submittedText</p>
}
@code {
private UserInputModel userInput = new UserInputModel();
private string? submittedText;
protected override void OnInitialized()
{
userInput.InputText = "Hello World!";
}
private void HandleSubmit()
{
submittedText = userInput.InputText;
}
public class UserInputModel
{
public string? InputText { get; set; }
}
}
using Test.Components;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddRazorComponents()
.AddInteractiveServerComponents();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error", createScopeForErrors: true);
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseAntiforgery();
app.MapRazorComponents<App>()
.AddInteractiveServerRenderMode();
app.Run();
Ensure that you have applying the render mode to the entire app.
This should resolve the component from re-rendering and result in the value of userInput.InputText
being reset to "Hello World!".
App.razor
<HeadOutlet @rendermode="InteractiveServer" />
<Routes @rendermode="InteractiveServer" />