Search code examples
kendo-uikendo-asp.net-mvc

How to use ajax to post Kendo upload files to controller


When i use ajax to post the form data to controller, i cannot get the files when using Kendo upload. I used IEnumerable but i only can get the date value and the file is null. May i know how to make it work? Thanks. (I use ajax because i need call the onsuccess event)

//Here is the form control in view

<div class="editForm">
@using (Html.BeginForm("UpdateReportFix", "Defect", FormMethod.Post, new { id = "form" }))
{
    @Html.HiddenFor(model => model.DefectFixID)
    <div>
        @Html.Label("Report Date")
    </div>
    <div>
        @(Html.Kendo().DatePickerFor(model => model.ReportDate)
                      .Name("ReportDate")
                      .Value(DateTime.Now).Format("dd/MM/yyyy")
                      .HtmlAttributes(new { @class = "EditFormField" })
        )
        @Html.ValidationMessageFor(model => model.ReportDate)
    </div>

        <div>
            @Html.Label("Photos")
            <br />
            <span class="PhotosMessage">System Allow 2 Pictures</span>
        </div>

        <div class="k-content">
            @(Html.Kendo().Upload()
                .Name("files")  <-----i cannot get this value in controller
            )
        </div>

            <br />
            <div class="col-md-12 tFIx no-padding">
                @(Html.Kendo().Button().Name("Cancel").Content("Cancel").SpriteCssClass("k-icon k-i-close"))
                @(Html.Kendo().Button().Name("submit").Content("Submit").SpriteCssClass("k-icon k-i-tick"))
            </div>
}

//script

$('form').submit(function (e) {
    e.preventDefault();
    var frm = $('#form');
    $.ajax({
        url: '@Url.Action("UpdateReportFix")',
        type: 'POST',
        data: frm.serialize(),
        beforeSend: function () {
        },
        onsuccess: function () { },
        success: function (result) { },
        error: function () { }
    });
});


Solution

  • For "Uploading files using Ajax & Retain model values after Ajax call and Return TempData as JSON" try the following example:


    View:

    @using (Html.BeginForm("Create", "Issue", FormMethod.Post,
    new { id = "frmCreate", enctype = "multipart/form-data" }))
    { 
        <div id="divMessage" class="empty-alert"></div>
        @Html.LabelFor(m => m.FileAttachments, new { @class = "editor-label" })
        @(Html.Kendo().Upload()
            .HtmlAttributes(new { @class = "editor-field" })
            .Name("files")
        )
    }
     
     
    <script>
        $(function () {
     
            //Populate model values of the partialview after form reloaded (in case there is a problem and returns from Controller after Submit)
            $('form').submit(function (event) {
                event.preventDefault();
                showKendoLoading();
                var selectedProjectId = $('#ProjectID').val(); /* Get the selected value of dropdownlist */
                if (selectedProjectId != 0) {
                    //var formdata = JSON.stringify(@Model); //For posting uploaded files use as below instead of this
                    var formdata = new FormData($('#frmCreate').get(0));
     
                    $.ajax({
                        type: "POST",
                        url: '@Url.Action("Create", "Issue")',
                        //contentType: "application/json; charset=utf-8", //For posting uploaded files use as below instead of this
                        data: formdata,
                        dataType: "json",
                        processData: false, //For posting uploaded files we add this
                        contentType: false, //For posting uploaded files we add this
                        success: function (response) {
                            if (response.success) {
                                window.location.href = response.url;
                                @*window.location.href = '@Url.Action("Completed", "Issue", new { /* params */ })';*@
                            }
                            else if (!response.success) {
                                hideKendoLoading();
                                //Scroll top of the page and div over a period of one second (1,000 milliseconds = 1 second).
                                $('html, body').animate({ scrollTop: (0) }, 1000);
                                $('#popupDiv').animate({ scrollTop: (0) }, 1000);
                                var errorMsg = response.message;
                                $('#divMessage').html(errorMsg).attr('class', 'alert alert-danger fade in');
                                $('#divMessage').show();
                            }
                            else {
                                var errorMsg = null;
                                $('#divMessage').html(errorMsg).attr('class', 'empty-alert');
                                $('#divMessage').hide();
                            }
                        }
                    });
                }
                else {
                    $('#partialPlaceHolder').html(""); //Clear div
                }
     
            });
     
        });
    </script> 
    

    Controller:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Exclude = null)] Model viewModel, IEnumerable<HttpPostedFileBase> files)
    {
        //...
        return Json(new { success = false, message = "Max. file size is 10MB" }, JsonRequestBehavior.AllowGet);
    }