Blazor - إنشاء نموذج ديناميكي باستخدام Loop و Binding
🔹 Blazor - إنشاء نموذج ديناميكي باستخدام Loop و Binding
في بعض الأحيان تحتاج إلى إنشاء نموذج يحتوي على عناصر متعددة يتم توليدها ديناميكيًا مثل قائمة مهام أو عناصر جدول يمكن تعديلها.
Blazor يسمح لك بتنفيذ ذلك بسهولة باستخدام حلقات @foreach
مع EditForm
وربط البيانات باستخدام @bind-Value
.
🧪 مثال عملي: نموذج لإدخال عناصر متعددة
public class TaskItem
{
public string? Description { get; set; }
public bool IsDone { get; set; }
}
@using System.ComponentModel.DataAnnotations
<EditForm Model="@this" OnValidSubmit="Save">
<DataAnnotationsValidator />
@foreach (var task in Tasks)
{
<div class="mb-2">
<InputText class="form-control d-inline-block w-75" @bind-Value="task.Description" />
<InputCheckbox class="form-check-input ms-2" @bind-Value="task.IsDone" />
</div>
}
<button class="btn btn-success" type="submit">💾 حفظ القائمة</button>
</EditForm>
@code {
private List<TaskItem> Tasks = new()
{
new TaskItem(),
new TaskItem(),
new TaskItem()
};
void Save()
{
Console.WriteLine("✅ تم حفظ المهام:");
foreach (var t in Tasks)
Console.WriteLine($"- {t.Description} ✔️{t.IsDone}");
}
}
تعليقات
إرسال تعليق