简体   繁体   English

使用弹出表单上传文件,MVC 和 AJAX 始终为“NULL”

[英]File upload using popup form, MVC and AJAX always 'NULL'

I'm using the code from this tutorial to upload rows to a SQL Server table and one of the new requirements it's getting files stored into the server for "Evidence" purposes, so in the form I have the following code:我正在使用本教程中的代码将行上传到 SQL Server 表,这是将文件存储到服务器中以用于“证据”目的的新要求之一,因此在表单中我有以下代码:

@using (Html.BeginForm("AnadirLic", "Licencia", FormMethod.Post, new { enctype = "multipart/form-data", onsubmit = "return SubmitForm(this)" }))
{
    @Html.HiddenFor(model => model.idLicencia)
<div class="form-group">
                    <label>Tipo de especialista: </label>

                    @Html.DropDownList("tipoEspecialista", new List<SelectListItem>{
                    new SelectListItem{ Value="1", Text = "Medico"},
                    new SelectListItem{ Value="2", Text = "Dentista"},
                    new SelectListItem{ Value="3", Text = "Matrona"},})

                    <small class="form-text text-muted">Ejercicio</small>
                </div>
                <div class="form-group">
                    <label>Cargar Evidencia</label>
                    @*@Html.TextBoxFor(model => model.rutaEvidencia, new { @class = "form-control", @type = "file" })*@
                    @*@Html.TextBoxFor(model => model.rutaEvidencia, new { @class = "form-control", @type = "file", enctype = "multipart/form-data" })*@
                    <input type="file" id="FileUpload" />
                    <small class="form-text text-muted">Máximo 4MB, .pdf, .jpg, .png</small>
                </div>

                <div class="input-group">
                    <input type="submit" value="Subir" class="btn btn-primary" style="margin-right:10px"/>
                    <input type="reset" value="Limpiar campos" class="btn btn-primary" />
                </div>

And the AJAX function looks like this: AJAX 函数如下所示:

 <script> function PopupForm(url) { var formDiv = $('<div/>'); $.get(url) .done(function (response) { formDiv.html(response); Popup = formDiv.dialog({ autoOpen: true, resizable: true, title: 'Llenar nuevo reposo', height: 500, width: 1300, close: function () { Popup.dialog('destroy').remove(); } }) } ) } function SubmitForm(form) { $.validator.unobtrusive.parse(form); // FILE VALIDATOR / COUNT var totalFiles = document.getElementById("FileUpload").files.length; for (var i = 0; i < totalFiles; i++) { var archivo = document.getElementById("FileUpload").files[i]; form.append("FileUpload", archivo); } //IF VALID UPLOAD TO SQL if ($(form).valid()) { $.ajax({ type: "POST", url: form.action, data: $(form).serialize(), success: function (data) { if (data.success) { Popup.dialog('close'); $('#tablaLicencia').DataTable().ajax.reload() $.notify(data.message, { globalPosition: "top center", className: "success" }) } } }); } return false; } </script>

Finally the C#:最后是 C#:

[HttpPost]
public ActionResult AnadirLic(licenciasUsuario lic)
{
    using (TH_mantenedorLicenciasEntities db = new TH_mantenedorLicenciasEntities())
    {
        var fechaYMD = DateTime.Now.ToString("yyyyMMdd");
        var fechaHM = DateTime.Now.ToString("hhmm");
        var InputFileName = "";
        var ServerSavePath = "";

        for (int i = 0; i < Request.Files.Count; i++)
        {
            var archivo = Request.Files[i];

            InputFileName = Path.GetFileName(archivo.FileName);
            ServerSavePath = Path.Combine(Server.MapPath("~/evCargadas") + fechaYMD + "_" + fechaHM + "_" + InputFileName);
            //Save file to server folder  
            archivo.SaveAs(ServerSavePath);
        }

        ViewBag.Message = "Archivo subido correctamente.";

        db.licenciasUsuario.Add(lic);

        db.SaveChanges();

        //UPDATE CON RUTA DE ARCHIVO
        lic.rutaEvidencia = ServerSavePath;

        db.Entry(lic).State = System.Data.Entity.EntityState.Modified;

        db.SaveChanges();

        return Json(new { success = true, message = "Licencia guardada exitosamente." }, JsonRequestBehavior.AllowGet);
    }
}

What I've faced is that the FileUpload is always null and using HttpPostFileBase returns the same, therefore the method throws a null exception to the Entity and based on some answers on SO, MVC conflicts with these kind of ajax apps.我所面临的是 FileUpload 始终为空并且使用HttpPostFileBase返回相同的值,因此该方法向实体抛出空异常,并且基于 SO 上的一些答案,MVC 与此类 ajax 应用程序发生冲突。

System.Data.Entity.Validation.DbEntityValidationException: 'Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.'

Is it possible to emulate a function that allows/force a file upload into a project folder using the same popup thing?是否可以使用相同的弹出窗口模拟允许/强制将文件上传到项目文件夹的功能?

<input type="file" id="FileUpload" /> lets you to select single file. <input type="file" id="FileUpload" />允许您选择单个文件。 In submit function you are accessing files property which is available only for multiple files selection.在提交功能中,您正在访问文件属性,该属性仅可用于多个文件选择。

So, either add multiple to your input tag <input type="file" id="FileUpload" multiple />因此,要么将多个添加到您的输入标签<input type="file" id="FileUpload" multiple />

or modify submit function to use "value" property instead of files property.修改提交函数以使用“值”属性而不是文件属性。

function SubmitForm(form) {
    $.validator.unobtrusive.parse(form);
// FILE VALIDATOR / COUNT
    /*var totalFiles = document.getElementById("FileUpload").files.length;
    for (var i = 0; i < totalFiles; i++) {
        var archivo = document.getElementById("FileUpload").files[i];
        form.append("FileUpload", archivo);
    }*/
    var archivo = document.getElementById("FileUpload").Value;
    form.append("FileUpload", archivo);
//IF VALID UPLOAD TO SQL
    if ($(form).valid()) {
        $.ajax({
            type: "POST",
            url: form.action,
            data: $(form).serialize(),
            success: function (data) {
                if (data.success) {
                    Popup.dialog('close');

                    $('#tablaLicencia').DataTable().ajax.reload()

                    $.notify(data.message, {
                        globalPosition: "top center",
                        className: "success"
                    })

                }
            }
        });
    }
    return false;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM