【问题标题】:How to use ajax to post Kendo upload files to controller如何使用 ajax 将剑道上传文件发布到控制器
【发布时间】:2016-05-05 11:44:17
【问题描述】:

当我使用 ajax 将表单数据发布到控制器时,使用剑道上传时我无法获取文件。我使用了 IEnumerable 但我只能获取日期值并且文件为空。我可以知道如何使它工作吗?谢谢。 (我使用 ajax 是因为我需要调用 onsuccess 事件)

//这里是视图中的表单控件

<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>
}

//脚本

$('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 () { }
    });
});

【问题讨论】:

    标签: kendo-ui kendo-asp.net-mvc


    【解决方案1】:

    对于“使用 Ajax 上传文件并在 Ajax 调用后保留模型值并将 TempData 作为 JSON 返回”尝试以下示例:


    查看:

    @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> 
    


    控制器:

    [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);
    }
    

    希望这会有所帮助...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-06
      • 1970-01-01
      • 2013-02-02
      • 1970-01-01
      • 2016-12-07
      • 1970-01-01
      相关资源
      最近更新 更多