Search code examples
c#razorblazor

Radzen Validation in a ForEach


I have a Foreach which contains a RadzenNumeric and Validation for it. The issue I am having is that the Name and Component are the same for every item in the Foreach. So if 1 out of 10 have a value then they all do not show the validation error.

Question is, what is the best approach to make the name Unique? Is there a way to do a Counter within the Foreach and just add that value to the end of the Name and Componenet?

@foreach (Models.Ingredients.MeasuredIngredient measuredIngredient in CompoundIngredient.MeasuredIngredients)
{
    <div class="ingredient-seperator"></div>
    <div class="row ingredient">
        <div class="amountInput col-6 col-md-2">
            <RadzenNumeric class="newInput" Name="Amount" @bind-Value="measuredIngredient.Amount" TValue="decimal" Min="0"></RadzenNumeric>
            <RadzenRequiredValidator class="rz-message rz-messages-error rz-message-popup newInputValidation" Component="Amount" Text="Amount is required" DefaultValue="0" Popup="true" />
        </div>
        
    </div>
}

Solution

  • It should be possible to number them.

    @{ var index = 0; }
    
    @foreach (Models.Ingredients.MeasuredIngredient measuredIngredient in CompoundIngredient.MeasuredIngredients)
    {
        index += 1;
        <RadzenNumeric class="newInput" Name="@("Amount"+index)" @bind-Value="measuredIngredient.Amount" TValue="decimal" Min="0"></RadzenNumeric>
        <RadzenRequiredValidator class="rz-message ..." Component="@("Amount"+index)" Text="Amount is required" ... />
    }