dotnet / aspnetcore

ASP.NET Core is a cross-platform .NET framework for building modern cloud-based web applications on Windows, Mac, or Linux.
https://asp.net
MIT License
35.36k stars 9.99k forks source link

Blazor forms validation system: Help needed regarding EditContex.FieldClass method #9384

Closed enetstudio closed 5 years ago

enetstudio commented 5 years ago

I'm trying to understand the code in https://github.com/aspnet/AspNetCore/blob/7a1a53d76d62783ae33f116309c5d3745f00dd94/src/Components/test/testassets/BasicTestApp/FormsTest/NotifyPropertyChangedValidationComponent.razor, which is quit clear to me:

The object editContext is instantiated and used in various places in the file. But I don't understand where "context" comes from in this snippet: User name: taken from this file: https://github.com/aspnet/AspNetCore/blob/master/src/Components/test/testassets/BasicTestApp/FormsTest/SimpleValidationComponent.razor

Note that in the last example the attribute Model of the EditForm is assigned a value; and thus, EditForm creates an instance of EditContext, which, I guess, can be accessed via the public property EditContext, but alas, it is not clear where where "context" comes from. Shouldn't it be: class="@EditContext.FieldClass(() => UserName)"

Thank you for any help you can offer here...

RemiBou commented 5 years ago

EditContext is a cascading parameter from the EditForm. The editForm will instantiate it if none are coming from parent component.

Try to have a look to the generated class in obj/debug folder for understanding how it works and how the context variable is available.

enetstudio commented 5 years ago

RemiBou: The editForm will instantiate it if none are coming from parent component.

That is exactly what I am saying in the comment above: Note that in the last example the attribute Model of the EditForm is assigned a value; and thus, EditForm creates an instance of EditContext, which, I guess, can be accessed via the public property EditContext, but alas, it is not clear where where "context" comes from. Shouldn't it be: class="@EditContext.FieldClass(() => UserName)"

Can you answer me where the word "context" in class="@context.FieldClass(() => UserName)" comes from ?

RemiBou commented 5 years ago

Sorry I didn't fully understand your question.

SteveSandersonMS commented 5 years ago

The word context is a built-in default used by all templated components: https://visualstudiomagazine.com/articles/2018/12/01/blazor-templated-components.aspx

You can optionally override the name, e.g.,

<EditForm Model="..." Context="myEditContext">
    <input bind="..." class="@myEditContext.FieldClass(() => UserName)" />
</EditForm>
enetstudio commented 5 years ago

I got it...thank you, maestro.