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

Creating Dynamic Forms from a JSON File

Environment

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

Description

How can I generate dynamic Telerik UI for ASP.NET MVC 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 IActionResult 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());
                    }
                }
            })
            )
        }
    

More ASP.NET MVC Form Resources

See Also

In this article