dotnet / AspNetCore.Docs

Documentation for ASP.NET Core
https://docs.microsoft.com/aspnet/core
Creative Commons Attribution 4.0 International
12.6k stars 25.29k forks source link

Button to clear or reset value #31354

Closed KristinBethea closed 6 months ago

KristinBethea commented 9 months ago

Description

[Enter feedback here] It would be nice if the documentation and examples showed us how to clear or reset the values.

Page URL

https://learn.microsoft.com/en-us/aspnet/core/blazor/forms/input-components?view=aspnetcore-8.0

Content source URL

https://github.com/dotnet/AspNetCore.Docs/blob/main/aspnetcore/blazor/forms/input-components.md

Document ID

52ee411b-69fe-c0bc-5305-846d9384ebbd

Article author

@guardrex

github-actions[bot] commented 9 months ago

🎉🥳 Happy New Year! 💃🕺

A green dinosaur 🦖 will be along shortly to assist. Stand-by ........

guardrex commented 9 months ago

Hello @KristinBethea ... Unless you had something specific in mind, one would just set the field or property back to its initial state, possibly also calling StateHasChanged() if you need to trigger a re-rendering.

guardrex commented 9 months ago

Yeah ... it's fairly striaightforward just resetting the model. For example using the Form1 component, it just needs a button ...

<button @onclick="ClearForm">Clear form</button>

... and a method to reset the model ...

private void ClearForm()
{
    model = new();
}

It doesn't even require calling StateHasChanged() in that case because that event handler triggers a re-render.

Unless you had something specific in mind, I think we'll wait to see if devs get confused about it.

guardrex commented 9 months ago

Same principle applies to setting values to model fields and properties ...

<button @onclick="SetName">Set Name to 'GooberRex'</button>

... with ...

private void SetName()
{
    model.Name = "GooberRex";
}

image

KristinBethea commented 9 months ago

That would be outside the <EditForm then, right?

guardrex commented 9 months ago

Yes ... but I don't think triggering the event from inside the EditForm would be a problem. I'll try that, too, just to confirm my suspicion. I'm sure I've done it at some time in the past, but it's nice to check with all of the new Blazor Web App bits that just rolled out.

guardrex commented 9 months ago

Confirmed! ... yes ... it works from wherever. Re-rendering the form is going to rebind the model, so it doesn't really matter where that comes from.

I'm cool with adding some remarks on this. It will receive a low priority at the moment because of all of the .NET 8 doc work that I'm still buried under ⛰️⛏️😅. I'll get to it as soon as I can. Thanks for the issue!

KristinBethea commented 9 months ago

Yes, definitely a lot of .NET 8 to work on first. :) Thanks for all you do!