New to Telerik UI for ASP.NET Core? Download free 30-day trial

Creating Dynamic Forms from a JSON File

Environment

Product Telerik UI for ASP.NET Core Form
Progress Telerik UI for ASP.NET Core version Created with the 2023.3.1114 version

Description

How can I generate dynamic Telerik UI for ASP.NET Core Forms through a JSON file?

Solution

  1. Create the JSON file with the following structure and save it into the application.

        [{
            "Id": 16014,
            "Properties": [
                {
                    "Property": "Name",
                    "EditorType": "TextBox"
                },
                {
                    "Property": "StartDate",
                    "EditorType": "DatePicker"
                },
                {
                    "Property": "IsActive",
                    "EditorType": "CheckBox"
                },
                {
                    "Property": "Country",
                    "EditorType": "DropDownList"
                }
            ]
        },
        {
            "Id": 18231,
            "Properties": [
                {
                    "Property": "Name",
                    "EditorType": "TextBox"
                },
                {
                    "Property": "IsActive",
                    "EditorType": "CheckBox"
                }
            ]
        }]
    
  2. Create the following Models:

    • FormViewModel—The Model that defines the properties and structure of the JSON data.

          public class FormViewModel
          {
              public int Id { get; set; } // The unique Form Id.
              public List<FormItems> Properties { get; set; } // The properties that will be used to populate the Form items.
          }
      
    • FormItems—The Model that represents the Form item.

          public class FormItems
          {
              public string Property { get; set; } // The name of the property that will bind to each Form item.
              public string EditorType { get; set; } // The name of the editor.
          }
      
    • UserViewModel—The Model to which each Form will bind.

          public class UserViewModel
          {
              public string Name { get; set; }
              public DateTime StartDate { get; set; }
              public bool IsActive { get; set; }
              public int Country { get; set; }
          }
      
  3. Use the JsonConvert.DeserializeObject<T>() method to convert the JSON content from the file into a List<FormViewModel> objects.

        using Newtonsoft.Json;
    
        public ActionResult Index()
        {
            var formDataitems = PopulateFormItems();
            return View(formDataitems);
        }
    
        private List<FormViewModel> PopulateFormItems()
        {
            var path = Path.Combine("wwwroot/formData.json");
            var items = new List<FormViewModel>();
            items = JsonConvert.DeserializeObject<List<FormViewModel>>(System.IO.File.ReadAllText(path));
            return items;
        }
    
  4. Access the Model collection in the View and loop through each FormViewModel record to generate the respective Forms. Within the Form Items() configuration, loop through the nested Properties collection and define the editor of each item based on the value of the EditorType property.

        @model List<FormViewModel>
    
        @foreach (var item in Model)
        {
            @(Html.Kendo().Form<UserViewModel>()
            .Name("form_" + item.Id)
            .HtmlAttributes(new { action = "/Home/SaveForm", method = "POST" })
            .FormData(new UserViewModel())
            .Orientation("horizontal")
            .Validatable(v =>
            {
                v.ValidateOnBlur(true);
                v.ValidationSummary(vs => vs.Enable(false));
            })
            .Items(i =>
            {
                foreach (var prop in item.Properties)
                {
                    if (prop.EditorType == "DatePicker")
                    {
                        i.Add()
                        .Field(prop.Property)
                        .Label(l => l.Text(prop.Property))
                        .Editor(e => e.DatePicker());
                    }
                    else if (prop.EditorType == "DropDownList")
                    {
                        i.Add()
                        .Field(prop.Property)
                        .Label(l => l.Text(prop.Property))
                        .Editor(e =>
                        {
                            e.DropDownList()
                            .DataTextField("Text")
                            .DataValueField("Value")
                            .BindTo(new List<SelectListItem>() {
                                new SelectListItem() {
                                    Text = "Country 1",
                                    Value = "1"
                                },
                                new SelectListItem() {
                                    Text = "Country 2",
                                    Value = "2"
                                },
                                new SelectListItem() {
                                    Text = "Country 3",
                                    Value = "3"
                                }
                            });
                        });
                    }
                    else if (prop.EditorType == "CheckBox")
                    {
                        i.Add()
                        .Field(prop.Property)
                        .Label(l => l.Text(prop.Property))
                        .Editor(e => e.CheckBox());
                    }
                    else
                    {
                        i.Add()
                        .Field(prop.Property)
                        .Label(l => l.Text(prop.Property))
                        .Editor(e => e.TextBox());
                    }
                }
            })
            )
        }
    
        @addTagHelper *, Kendo.Mvc
    
        @{
            var countries = new List<SelectListItem>()
            {
                new SelectListItem() {
                    Text = "Country 1",
                    Value = "1"
                },
                new SelectListItem() {
                    Text = "Country 2",
                    Value = "2"
                },
                new SelectListItem() {
                    Text = "Country 3",
                    Value = "3"
                }
            };
        }
        @model List<FormViewModel>
    
        @foreach (var item in Model)
        {
            <kendo-form name="form_@item.Id" form-data="new UserViewModel()" orientation="horizontal" action="SaveForm" method="POST">
                <form-items>
                    @foreach (var prop in item.Properties)
                    {
                        if (prop.EditorType == "DatePicker")
                        {
                            <form-item field=@prop.Property>
                                <item-label text=@prop.Property />
                                <datepicker-editor />
                            </form-item>
                        }
                        else if (prop.EditorType == "DropDownList")
                        {
                            <form-item field=@prop.Property>
                                <item-label text=@prop.Property />
                                <dropdownlist-editor 
                                    datatextfield="Text"
                                    datavaluefield="Value" 
                                    bind-to="countries" />
                            </form-item>
                        }
                        else if (prop.EditorType == "CheckBox")
                        {
                            <form-item field=@prop.Property >
                                <switch-editor>
                                    <messages checked="Active" unchecked="Inactive" />
                                </switch-editor>
                            </form-item>
                        }
                        else
                        {
                            <form-item field=@prop.Property>
                                <item-label text=@prop.Property />
                                <textbox-editor />
                            </form-item>
                        }
    
                    }
                </form-items>
                <validatable validate-on-blur="true" />
            </kendo-form>
        }
    

More ASP.NET Core Form Resources

See Also

In this article