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

Form Integration

Usually, developers integrate the Upload component into a form, ensuring that uploaded files are submitted and processed together with other form fields like textboxes, dropdowns, and more.

You can define the Upload component as an editor in both a standard HTML form and a Telerik UI for ASP.NET Core Form.

Upload in Telerik UI for ASP.NET Core Form

  1. Declare a field in the Form component that binds to a collection of IFormFile and specify the Upload component as an editor. For example, you can use the EditorTemplateId() option that accepts the name of an external Kendo UI template.

        public class FormViewModel
        {
            public string OrderName { get; set; }
    
            public decimal Freight { get; set; }
    
            public IEnumerable<IFormFile> Files { get; set; }
        }
    
        @(Html.Kendo().Form<FormViewModel>()
            .Name("exampleForm")
            .HtmlAttributes(new { action = @Url.Action("SubmitForm", "Home"), method = "POST" })
            .Validatable(v =>
            {
                v.ValidateOnBlur(true);
                v.ValidationSummary(vs => vs.Enable(true));
            })
            .Items(items =>
            {
                items.Add()
                    .Field(f => f.OrderName)
                    .Label(l => l.Text("Order name:"));
                items.Add()
                    .Field(f => f.Freight)
                    .Label(l => l.Text("Freight:"))
                    .Editor(x => x.NumericTextBox().Min(10).Max(1000));
                items.Add()
                    .Field(f => f.Files)
                    .EditorTemplateId("uploadEditorTemplate");
            })
        )
    
        <script type="text/x-kendo-template" id="uploadEditorTemplate">
            @(Html.Kendo().Upload()
                .Name("Files")
            )
        </script>
    
    @addTagHelper *, Kendo.Mvc
    
    @model FormViewModel
    
    <kendo-form name="exampleForm" form-data="@Model" method="POST">
        <validatable validate-on-blur="true" validation-summary="true" />
        <form-items>
            <form-item field="OrderName">
                <item-label text="Name:" />
            </form-item>
            <form-item field="Freight">
                <item-label text="Freight:" />
                <numerictextbox-editor min="10" max="1000"></numerictextbox-editor>
            </form-item>
            <form-item field="Files" editor-handler="uploadEditor">
            </form-item>
        </form-items>
    </kendo-form>
    
    <script type="text/javascript">
        function uploadEditor(container, options) {
            $('<input type="file" name="Files" id="Files"/>')
                .appendTo(container)
                .kendoUpload({}); //set additional Upload configuration if desired
        }
    </script>
    
  2. Handle the submit event of the Form, prevent its default action, and gather the uploaded files along with the Form fields. Then, trigger an AJAX request to the server to post the Form data.

    <script type="text/javascript">
        $(document).ready(function () {
            $("#exampleForm").submit(function (e) {
                e.preventDefault(e);
                var formData = new FormData(); // 1. Create a new FormData instance.
                var upload = $("#Files").getKendoUpload(); // 2. Obtain the Upload widget incarnation's object reference.
                var files = upload.getFiles(); // 3. Gather the uploaded files.
    
                var serializedArray = $("#exampleForm").serializeArray(); // 4. Serialize the form data in to key-value pairs.
    
                for (var i = 0; i < serializedArray.length; i++) { // 5. Traverse through each of the key-value pairs.
                    var key = serializedArray[i]['name'];
                    var value = serializedArray[i]['value'];
                    formData.append(key, value); // 6. Append current key-value pair to the newly created Form Data from step 1.
                }
    
                for (var i = 0; i < files.length; i++) { // 7. Iterate through each of the uploaded and append them to the Form data.
                    let file = files[i].rawFile;
                    formData.append("files", file);
                }
    
                $.ajax({ // 8. Make an AJAX request by posting the form data.
                    type: "POST",
                    url: "@Url.Action("SaveForm", "Home")",
                    data: formData,
                    processData: false,
                    contentType: false,
                    dataType: "json",
                    success: function (response) {
                        if (response.success) { // 9. If the request is completed successfully, clear the Form fields.
                            alert("Files Uploaded!");
                            $("#exampleForm").getKendoForm().clear();
                        }
                    },
                    error: function() {
                        alert("Request failed");
                    }
                });
            });
        });
    </script>
    
  3. Access the received Form data on the server and process the uploaded files.

        [HttpPost]
        public JsonResult SaveForm(FormViewModel formData)
        {
            if (formData.Files != null)
            {
                foreach (var file in formData.Files)
                {
                    var fileContent = ContentDispositionHeaderValue.Parse(file.ContentDisposition);
                    var fileName = Path.GetFileName(fileContent.FileName.Trim('"'));
                    var physicalPath = Path.Combine("wwwroot/uploadedFiles", fileName); // Save the files in "wwwroot/uploadedFiles" application directory.
                    using (var stream = new FileStream(physicalPath, FileMode.Create))
                    {
                        file.CopyTo(stream);
                    }
                }
            }
            // Return the respective request response if the files are uploaded successfully.
            return Json(new { success = true });
        }
    

Upload in an HTML Form

  1. Create an HTML form and declare the Upload component as an editor of the Files model property.

        public class FormViewModel
        {
            public string OrderName { get; set; }
    
            public decimal Freight { get; set; }
    
            public IEnumerable<IFormFile> Files { get; set; }
        }
    
    @model FormViewModel
    
    <form id="exampleForm" action='@Url.Action("Submit")' method="post">
        <div class="k-form-group">
            <div class="k-form-field">
                @(Html.Kendo().TextBoxFor(m => m.OrderName)
                    .Label(l => l.Content("Name:").Floating(true))
                )
            </div>
            <div class="k-form-field">
                @(Html.Kendo().NumericTextBoxFor<decimal>(m => m.Freight)
                    .Min(10)
                    .Max(1000)
                    .Label(l => l.Content("Freight:").Floating(true))
                )
            </div>
            <div class="k-form-field">
                @(Html.Kendo().Upload()
                    .Name("Files")
                )
            </div>
        </div>
        <button type="submit" class="k-button k-button-solid-primary k-button-solid k-button-md k-rounded-md">Submit</button>
    </form>
    
    @addTagHelper *, Kendo.Mvc
    
    @model FormViewModel
    
    <form id="exampleForm" action='@Url.Action("Submit")' method="post">
        <div class="k-form-group">
            <div class="k-form-field">
                <kendo-textbox for="OrderName">
                    <textbox-label content="Name:" floating="true"/>
                </kendo-textbox>
            </div>
            <div class="k-form-field">
                <kendo-numerictextbox for="Freight" min="10" max="1000">
                    <numerictextbox-label content="Freight:" floating="true"/>
                </kendo-numerictextbox>
            </div>
            <div class="k-form-field">
                <kendo-upload name="Files">
                </kendo-upload>
            </div>
        </div>
        <button type="submit" class="k-button k-button-solid-primary k-button-solid k-button-md k-rounded-md">Submit</button>
    </form>
    
  2. Handle the submit event of the form, prevent its default action, and gather the uploaded files along with the form fields. Then, trigger an AJAX request to the server to post the form data.

    <script type="text/javascript">
        $(document).ready(function () {
            $("#exampleForm").submit(function (e) {
                e.preventDefault(e);
                var formData = new FormData(); // 1. Create a new FormData instance.
                var upload = $("#Files").getKendoUpload(); // 2. Obtain the Upload widget incarnation's object reference.
                var files = upload.getFiles(); // 3. Gather the uploaded files.
    
                var serializedArray = $("#exampleForm").serializeArray(); // 4. Serialize the form data in to key-value pairs.
    
                for (var i = 0; i < serializedArray.length; i++) { // 5. Traverse through each of the key-value pairs.
                    var key = serializedArray[i]['name'];
                    var value = serializedArray[i]['value'];
                    formData.append(key, value); // 6. Append current key-value pair to the newly created Form Data from step 1.
                }
    
                for (var i = 0; i < files.length; i++) { // 7. Iterate through each of the uploaded and append them to the form data.
                    let file = files[i].rawFile;
                    formData.append("files", file);
                }
    
                $.ajax({ // 8. Make an AJAX request by posting the form data.
                    type: "POST",
                    url: "@Url.Action("SaveForm", "Home")",
                    data: formData,
                    processData: false,
                    contentType: false,
                    dataType: "json",
                    success: function (response) {
                        if (response.success) { // 9. If the request is completed successfully, clear the Form fields.
                            alert("Files Uploaded!");
                        }
                    },
                    error: function() {
                        alert("Request failed");
                    }
                });
            });
        });
    </script>
    
  3. Access the received form data on the server and process the uploaded files.

        [HttpPost]
        public JsonResult SaveForm(FormViewModel formData)
        {
            if (formData.Files != null)
            {
                foreach (var file in formData.Files)
                {
                    var fileContent = ContentDispositionHeaderValue.Parse(file.ContentDisposition);
                    var fileName = Path.GetFileName(fileContent.FileName.Trim('"'));
                    var physicalPath = Path.Combine("wwwroot/uploadedFiles", fileName); // Save the files in "wwwroot/uploadedFiles" application directory.
                    using (var stream = new FileStream(physicalPath, FileMode.Create))
                    {
                        file.CopyTo(stream);
                    }
                }
            }
            // Return the respective request response if the files are uploaded successfully.
            return Json(new { success = true });
        }
    

See Also

In this article