ASP.Net MVC Ajax.BeginForm文件上传响应问题

时间:2018-07-19 01:30:08

标签: javascript c# ajax asp.net-mvc forms

因此,我有一个允许用户上传文件的模式,我想返回一个json响应以说明上传是否成功并将其显示给最终用户。

目前我的观点是

@model int

<div id="modal_newSupportPlan" class="modal fade" style="display:none;">
<div class="modal-dialog">
    <div class="modal-content">
        <div class="modal-header bg-primary">
            <button type="button" class="close" data-dismiss="modal">x</button>
            <h6 class="modal-title">New Support Plan</h6>
        </div>
        @using (Ajax.BeginForm("CreateSupportPlan", "Client",
            new AjaxOptions() { OnSuccess = "getSupportPlanResult", HttpMethod = "post" },
            new { @Class = "form-horizontal", enctype = "multipart/form-data" }))
        {
            <div class="modal-body">
                <input name="ClientFK" value="@Model" style="display:none" />
                <div class="form-group" id="newsupportplan_error_plantype">
                    <label class="control-label col-sm-3">Type of Plan</label>
                    <div class="col-sm-9">
                        <select id="planType" name="PlanType" class="form-control">
                            <option></option>
                            <option value="1">Initial Plan</option>
                            <option value="2">Pre Employment Plan</option>
                            <option value="3">6 Month Plan</option>
                            <option value="4">12 Month Plan</option>
                            <option value="5">Ongoing Support Plan</option>
                        </select>
                    </div>
                </div>
                <div class="form-group" id="newsupportplan_error_StartDate">
                    <label class="control-label col-sm-3">Date</label>
                    <div class="col-sm-9">
                        <input type="text" class="form-control pickadate-accessibility" name="Date" />
                    </div>
                </div>
                <div class="form-group" id="newsuportplan_error_SLILevel">
                    <label class="control-label col-sm-3">Support Level</label>
                    <div class="col-sm-9">
                        <select id="SliLevel" name="SliLevel" class="form-control">
                            <option></option>
                            <option value="1">SLI 1</option>
                            <option value="2">SLI 2</option>
                            <option value="3">SLI 3</option>
                        </select>
                    </div>
                </div>
                <div class="form-group">
                    <label class="control-label col-sm-3">Upload File</label>
                    <div class="col-sm-9">
                        <input type="file" name="Blob" />
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-link" data-dismiss="modal">Close</button>
                <button type="submit" class="btn btn-primary">Save</button>
            </div>
        }
    </div>
</div>

我的Controller方法是这个

[HttpPost]
    public ActionResult CreateSupportPlan(ModelHelper.SupportPlanViewModel supportPlanDetails)
    {
        try
        {
            esp_storage_supportPlans espStorageSupportPlans = new esp_storage_supportPlans();
            bool validation = true;
            var errorList = new List<string>();
            var passList = new List<string>();

            if (string.IsNullOrEmpty(supportPlanDetails.PlanType.ToString()))
            {
                errorList.Add("SupportPlanType");
                validation = false;
            }
            else
            {
                passList.Add("SupportPlanType");
            }

            if (string.IsNullOrEmpty(supportPlanDetails.Date.ToString()))
            {
                errorList.Add("Date");
                validation = false;
            }
            else
            {
                passList.Add("Date");
            }

            if (string.IsNullOrEmpty(supportPlanDetails.SliLevel))
            {
                errorList.Add("SLILevel");
                validation = false;
            }
            else
            {
                passList.Add("SLILevel");
            }

            if (supportPlanDetails.Blob != null && supportPlanDetails.Blob.ContentLength > 0)
            {
                if (validation)
                {
                    var uploadedFile = new byte[supportPlanDetails.Blob.InputStream.Length];
                    supportPlanDetails.Blob.InputStream.Read(uploadedFile, 0, uploadedFile.Length);
                    espStorageSupportPlans.Blob = uploadedFile;
                    espStorageSupportPlans.ClientFK = supportPlanDetails.ClientFK;
                    espStorageSupportPlans.Date = Convert.ToDateTime(supportPlanDetails.Date);
                    espStorageSupportPlans.SliLevel = supportPlanDetails.SliLevel;

                    if (supportPlanDetails.PlanType == 1) espStorageSupportPlans.PlanType = "Initial Plan";
                    if (supportPlanDetails.PlanType == 2) espStorageSupportPlans.PlanType = "Pre Employment Plan";
                    if (supportPlanDetails.PlanType == 3) espStorageSupportPlans.PlanType = "6 Month Plan";
                    if (supportPlanDetails.PlanType == 4) espStorageSupportPlans.PlanType = "12 Month Plan";
                    if (supportPlanDetails.PlanType == 5) espStorageSupportPlans.PlanType = "Ongoing Support Plan";

                    string extension = Path.GetExtension(supportPlanDetails.Blob.FileName);
                    espStorageSupportPlans.Extn = extension;
                    espStorageSupportPlans.FileName = supportPlanDetails.Blob.FileName;

                    db.esp_storage_supportPlans.Add(espStorageSupportPlans);
                    db.SaveChanges();
                }
            }
            else
            {
                errorList.Add("Blob");
                validation = false;
            }

            if (!validation)
            {
                return Json(new { result = "Validation", errors = errorList, pass = passList }, JsonRequestBehavior.AllowGet);
            }

            return Json(new { result = "success" }, JsonRequestBehavior.AllowGet);
        }
        catch (Exception)
        {
            return Json(new { result = "failed" }, JsonRequestBehavior.AllowGet);
        }
    }

我的JavaScript是以下2部分 第一部分通过上传文件使表格生效

window.addEventListener("submit", function (e) {
    var form = e.target;
    if (form.getAttribute("enctype") === "multipart/form-data") {
        if (form.dataset.ajax) {
            e.preventDefault();
            e.stopImmediatePropagation();
            var xhr = new XMLHttpRequest();
            xhr.open(form.method, form.action);
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    if (form.dataset.ajaxUpdate) {
                        var updateTarget = document.querySelector(form.dataset.ajaxUpdate);
                        if (updateTarget) {
                            updateTarget.innerHTML = xhr.responseText;
                        }
                    }
                }
            };
            xhr.send(new FormData(form));
        }
    }
}, true);

我的第二部分是onsuccess函数,但这没有被触发。当我实现第一部分以获取表单上传时,并停止触发

function getSupportPlanResult(data) {
    console.log("here");
    if (data.result === "success") {
        opts.title = "Completed";
        type: "success";
        opts.text = "Support Plan created successfully.";
        opts.type = "success";
        new PNotify(opts);
        supportPlanTable.destroy();
        BuildDataTable_SupportPlan();
        $('#modal_newSupportPlan').modal('hide');
    } else {
        if (data.result === "validation") {
            console.log(data);
        } else {
            opts.title = "Somthing Went Wrong";
            opts.text = "Support Plan failed to create, please try again.";
            opts.addclass = "stack-custom-bottom bg-danger";
            opts.type = "error";
            new PNotify(opts);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您为什么不使用任何库来为您处理XHR呢?像axios?代码可能看起来像这样:

window.addEventListener("submit", e => {
    const form = e.target;
    if (form.getAttribute("id") === '<my_unique_id_of_this_element>') {
        axios({
           method: form.method,
           url: form.action,
           data: /* whatever payload you need to send */
        })
        .then(({data}) => getSupportPlanResult(data));               
    }
});