New to Telerik UI for ASP.NET Core? Start a free 30-day trial
Dynamically Adding and Removing Form Items
Environment
Product Version | 2022.2.621 |
Product | Grid for Progress® Telerik® UI for ASP.NET Core |
Description
How can I dynamically add and remove items in the Telerik UI for ASP.NET Core Form?
Solution
This example demonstrates how to add/remove fields dynamically in the "Phones" Form group. The implementation relies on the following key steps:
- Create a 'Add Phone" button and insert it in the Form when the page is loaded (function "insertAddPhoneButton()").
- Append a button to each "Phone" field to make it removable (function "insertRemovePhoneButton()").
- Handle the "click" event of the "Add Phone" button to insert a new Form field. Update the Form with the new item and the Form data by using the
setOptions()
method. - Handle the "click" event of the remove button to remove the specified "Phone" input.
Index.cshtml
@model ProjectName.Models.PersonViewModel
@(Html.Kendo().Form<PersonViewModel>()
.Name("exampleForm")
.HtmlAttributes(new { action = @Url.Action("Submit", "Home"), method = "POST" })
.Orientation("horizontal")
.FormData(Model)
.Layout("grid")
.Grid(g => g.Cols(2).Gutter(60))
.Items(items =>
{
items.AddGroup()
.Label("Personal details")
.Items(i =>
{
i.Add()
.Field(f => f.FirstName)
.Label(l => l.Text("First Name"));
i.Add()
.Field(f => f.LastName)
.Label(l => l.Text("Last Name"));
});
items.AddGroup()
.Label("Phones")
.Items(i =>
{
i.Add()
.Field(f => f.Phones[0])
.Label(l => l.Text("Phone 1"))
.Editor(e => e.MaskedTextBox().Mask("(999) 000-0000"));
i.Add()
.Field(f => f.Phones[1])
.Label(l => l.Text("Phone 2"))
.Editor(e => e.MaskedTextBox().Mask("(999) 000-0000"));
});
})
)
For a runnable example based on the code above, refer to the REPL example on dynamically adding and removing Form items.