Home > front end >  Blazor: How to set as Required a parameter for custom component
Blazor: How to set as Required a parameter for custom component

Time:12-30

Example:

I have the following class:

  public class WeatherForecast
    {
        public DateTime Date { get; set; }

        public int TemperatureC { get; set; }

        public int TemperatureF => 32   (int)(TemperatureC / 0.5556);

        [Required]
        public string? Summary { get; set; }
    }

where I set the property Summary to Required

I have a razor component where I set that property

<InputText DisplayName="Test" @bind-Value="Text"></InputText>

@code {

    [Parameter]
    public string? Text { get; set; }   

    [Parameter]
    public EventCallback<string> TextChanged { get; set; }

}

in this razor page I use the Edit Form to set it:

@using TestRequired.Data;

<EditForm Model="wheater">
    <ValidationSummary></ValidationSummary>
    <DataAnnotationsValidator />
    Component
    <TestEditorComponent @bind-Text="wheater.Summary" />
    Input Text
    <InputText DisplayName="Test" @bind-Value="wheater.Summary"></InputText>
    <button type="submit" >Submit</button>

</EditForm>
@code {
    WeatherForecast wheater = new WeatherForecast();

    private int currentCount = 0;

    private void IncrementCount()
    {
        currentCount  ;
    }
}

when I try to submit an empty string, I receive the following result:

My result

The first one, is my component and it is not highlighted. Instead the input text, is correctly red.

How can I automatic highlight my components in a form if the binded property in the Model is required?

Thank you!

CodePudding user response:

If you want to create a composite control of some type, you need to manually map the bind "triumvirate" like this into the child component:

@using System.Linq.Expressions;

<InputText DisplayName="Test" Value="Text" ValueChanged="TextChanged" ValueExpression="this.TextExpression" />

@code {
    [Parameter] public string? Text { get; set; }
    [Parameter] public EventCallback<string> TextChanged { get; set; }
    [Parameter] public Expression<Func<string>>? TextExpression { get; set; }
}

"Bind" is a Razor directive not C#.

  • Related