File upload MVC 5中的文件上载在引导模式中使用时返回null

File upload MVC 5中的文件上载在引导模式中使用时返回null,file-upload,asp.net-mvc-5,bootstrap-modal,File Upload,Asp.net Mvc 5,Bootstrap Modal,我正在尝试使用引导模式弹出窗口允许在模式弹出窗口上上载文件。 但对于type=“file”,它总是返回null 我尝试了以下解决方案,但没有成功: 它总是返回null。如果我直接将其作为单独的页面运行,那么它可以正常工作,但只会出现弹出问题 我试图在ajax上更改内容类型,但它给了我以下错误:“必需的防伪表单字段\uuu requestverificationtoken不存在” 我已经使用开发工具测试了page post的功能: 这是我的密码: 控制器: [HttpPost] [Valida

我正在尝试使用引导模式弹出窗口允许在模式弹出窗口上上载文件。 但对于type=“file”,它总是返回null

我尝试了以下解决方案,但没有成功:

它总是返回null。如果我直接将其作为单独的页面运行,那么它可以正常工作,但只会出现弹出问题

我试图在ajax上更改内容类型,但它给了我以下错误:“必需的防伪表单字段\uuu requestverificationtoken不存在”

我已经使用开发工具测试了page post的功能:

这是我的密码:

控制器: [HttpPost] [ValidateAntiForgeryToken] 公共异步任务创建([Bind(Include=“ID,FileName,Link,SourceType,Comments,SourceDate,DateCreated,DateModified,projectd”)]ProjectSource ProjectSource,HttpPostedFileBase uploadFile) { if(ModelState.IsValid) { //上传方法1 var fileSavePath=“”; if(HttpContext.Request.Files.AllKeys.Any()) { //从文件集合中获取上载的图像 var httpPostedFile=HttpContext.Request.Files[0]

                if (httpPostedFile != null)
                {
                    // Validate the uploaded image(optional)

                    // Get the complete file path
                    fileSavePath = (HttpContext.Server.MapPath("~/xyz/") + httpPostedFile.FileName);

                    // Save the uploaded file to "UploadedFiles" folder
                    httpPostedFile.SaveAs(fileSavePath);
                }
            }

              //upload method 2
            if (uploadFile != null && uploadFile.ContentLength > 0)
            {
                try
                {
                    string path = Path.Combine(Server.MapPath("~/xyz/"),
                                               Path.GetFileName(uploadFile.FileName));
                    uploadFile.SaveAs(path);
                    ViewBag.Message = "File uploaded successfully";
                }
                catch (Exception ex)
                {
                    ViewBag.Message = "ERROR:" + ex.Message.ToString();
                }
            }
            else
            {
                ViewBag.Message = "You have not specified a file.";
            }


            db.ProjectSources.Add(projectSource);
            await db.SaveChangesAsync();


            return " File : " + ViewBag.Message + " == " + fileSavePath;

        }


        return " File : " + ViewBag.Message +" === "+sb.ToString();
    }
视图:

@模型portal.Models.ProjectSource

@{ 布局=”

}

× 添加新源
@using (Html.BeginForm("Create", "ProjectSource", FormMethod.Post, new { enctype = "multipart/form-data" , @id="ajaxForm"}))
{

    @Html.AntiForgeryToken()

    <div class="modal-body">
        <div class="form-horizontal">
            @*@Html.ValidationSummary(true, "", new { @class = "text-danger" })*@

            <div class="form-group">
                @Html.Label("Source file", htmlAttributes: new { @class = "control-label col-md-3" })
                <div class="col-md-6">
                    @Html.EditorFor(model => model.FileName, new { htmlAttributes = new { @class = "form-control" } })

                    @*<input type="file" name="uploadFile" />*@
                    @Html.TextBox("uploadFile",null, new { @class = "form-control", type = "file" })

                    @*<a href="../ProjectSource/FileUpload" id="open_btn" class="btn btn-orange" target="_blank">Add file</a>*@
                    @Html.ValidationMessageFor(model => model.FileName, "", new { @class = "text-danger" })

                </div>
            </div>
            @*<div class="form-group">
                    <div class="col-md-10" id="files" style="padding-left:40px;">

                    </div>
                </div>*@
            <div class="form-group">
                @Html.LabelFor(model => model.Link, htmlAttributes: new { @class = "control-label col-md-3" })
                <div class="col-md-6">
                    @Html.EditorFor(model => model.Link, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Link, "", new { @class = "text-danger" })
                </div>
            </div>
            <div class="form-group">
                @Html.LabelFor(model => model.SourceType, htmlAttributes: new { @class = "control-label col-md-3" })
                <div class="col-md-6">
                    @Html.EditorFor(model => model.SourceType, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.SourceType, "", new { @class = "text-danger" })
                </div>
            </div>
            <div class="form-group">
                @Html.LabelFor(model => model.Comments, htmlAttributes: new { @class = "control-label col-md-3" })
                <div class="col-md-6" style="color:black;">
                    @Html.TextAreaFor(model => model.Comments, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Comments, "", new { @class = "text-danger" })
                </div>
            </div>
            <div class="form-group">
                @Html.LabelFor(model => model.SourceDate, htmlAttributes: new { @class = "control-label col-md-3" })
                <div class="col-md-6" style="color:black;">
                    @Html.EditorFor(model => model.SourceDate, new { htmlAttributes = new { @class = "form-control datepicker datefield" } })
                    @Html.ValidationMessageFor(model => model.SourceDate, "", new { @class = "text-danger" })
                </div>
            </div>
        </div>
    </div>
        <div class="modal-footer">
            <button class="btn btn-med btn-orange" data-dismiss="modal">Cancel</button>
            <input class="btn btn-med btn-orange" type="submit" name="submit" value="Add" />
        </div>
}
我希望得到良好的工作解决方案: 提前感谢您抽出时间


谢谢

我一直在使用这段代码来解决这个问题,ModelState.ispartials大约一年了。干杯

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

$('#modal').on('shown.bs.modal', function () {
  $.validator.unobtrusive.parse($(this));
});

$('#modal').on('hidden.bs.modal', function () {
  $('#spinner').remove();
});

$.ajaxSetup({ cache: false });

});

如果您想使用ajax上传文件,可能需要使用
FormData
。@StephenMuecke非常感谢…我试图使用FormData,但没有工作,因为没有将contentType=false和processData=false放入。但现在可以工作了…非常感谢…此代码的大部分与和完全相同。
        $.ajax({
            url: this.action,
            type: this.method,
            async: true,
            data: $(this).serialize(),
            contentType:this.enctype,
            success: function (result) {

                if (result) {
                alert(result)
                    //Refresh

                } else {
                   alert(result)
                }
            }
        });

        return false;
    });
$(function () {
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);

$('#modal').on('shown.bs.modal', function () {
  $.validator.unobtrusive.parse($(this));
});

$('#modal').on('hidden.bs.modal', function () {
  $('#spinner').remove();
});

$.ajaxSetup({ cache: false });

});