Dynamically add form fields?

Is it possible to add form fields to an already rendered page?

The situation is that I have a form for a model that has an embedded entity, and the relationship is one to many, and I don't know ahead of time how many there may be. I'd like to have the option to add a new "row" to the form, which accounts for additional items in the relationship.

The model form represents an item like this:

{
    "Id": 1,
    "Discriminator": "Distributor",
    "id": "Distributor|1",
    "ShippingCenters": [
        {
            "id": 1,
            "City": "Phoenix",
            "Street": "500 S 48th Street"
        },
        {
            "id": 2,
            "City": "Anaheim",
            "Street": "5650 Dolly Ave"
        }
    ],
}

Essentially I need to dynamically add 3 fields at a time to the form, every time an "add shipping center" button is clicked.

Field 1 - NumericTextBox (id)
Field 2 - TextBox (city)
Field 3 - TextBox (street)

I appreciate any guidance. :)


1 Reply

SP Sureshkumar P Syncfusion Team August 10, 2022 08:05 AM UTC

Hi Derek,

We have validated your requirement; we have created the sample by rendering the dynamic components using a button click event.

Find the code example here:

@using Syncfusion.EJ2

@using Newtonsoft.Json;

@using System;

@model WebApplication1.Controllers.ShippingCenters;

 

<button onclick="CreateComponent()">add shipping center</button>

<form id="DynamicForm"></form>

<script>

    function CreateComponent() {

        var form = document.getElementById("DynamicForm");

        var model = @Html.Raw(Json.Serialize(Model));

        if (typeof (model.id) === 'number'){

            var numericComponent = document.createElement("input");

            numericComponent.setAttribute("id", model.id);           

            form.appendChild(numericComponent);

            var numeric = new ej.inputs.NumericTextBox();

            numeric.appendTo("#" + numericComponent.getAttribute("id"));

        }

        if (typeof (model.city) === 'string') {

            var TextComponent = document.createElement("input");

            TextComponent.setAttribute("id", model.city);

            form.appendChild(TextComponent);

            var textbox = new ej.inputs.TextBox();

            textbox.appendTo("#" + TextComponent.getAttribute("id"));

        }

        if (typeof (model.street) === 'string') {

            var TextComponent = document.createElement("input");

            TextComponent.setAttribute("id", "street");

            form.appendChild(TextComponent);

            var textbox = new ej.inputs.TextBox();

            textbox.appendTo("#" + TextComponent.getAttribute("id"));

        }

    }

</script>

 

Find the sample in the attachment:

Regards,

Sureshkumar P


Attachment: ASPCore_6faa60c6.zip

Loader.
Up arrow icon