使用 AJAX 提交表单并提交阻止和发送文件控件 C# 的选定文件

form submission using ajax and submit prevent and send selected file of file control c#

本文关键字:提交 文件 控件 表单 AJAX 使用      更新时间:2023-09-26

在我的应用程序中,我有一个从部分视图呈现的表单。从该表单中,我想发送整个表单数据和文件控制的选定文件。表单提交使用 ajax 调用。要将所选文件保存到文件夹,我的代码如下所示:

JavaScript函数:

<script type="text/javascript">
    $(function () {
        $('#careerForm').submit(function (e) {
            e.stopPropagation();
            e.preventDefault();
            var formData = new FormData();
            var totalFiles = document.getElementById("fuUploadCV").files.length;
            for (var i = 0; i < totalFiles; i++) {
                var file = document.getElementById("fuUploadCV").files[i];
                formData.append("FileUpload", file);
            }
            $.ajax({
                type: "POST",
                url: '/CareerSurface/UploadImage/', //put your controller/action here
                data: formData,
                dataType: 'json',
                contentType: false,
                processData: false,
                beforeSend: function (xhr) {
                    //do something before send
                },
                success: function (data) {
                    //do something if success
                },
                error: function (data) {
                    //do something if error
                }
            });
        });
    });
</script>

目录 :

using (Html.BeginForm("ApplyNow", "CareerSurface", FormMethod.Post, new { enctype = "multipart/form-data", autocomplete = "off", id ="careerForm" })){
    <div class="Field-Label-Box">
        <label>First Name:<span> *</span></label>
    </div>
    <div class="Field-Value-Box">
        @Html.TextBoxFor(model => model.FirstName, new {  id = "txtFirstName", name = "txtFirstName", required = "required" })
        @Html.ValidationMessageFor(model => model.FirstName)
    </div>
    ......
    <div class="Field-Label-Box">
        <label>Upload CV:<span> *</span></label>
    </div>
    <div class="Field-Value-Box">
        @Html.TextBoxFor(model => model.ResumeUpload, new { type = "file", id = "fuUploadCV", name = "fuUploadCV", required = "required" })</div>
    <input type="submit" id="btnSave" value="Submit" name="btnSave"  />
}

C# :

[HttpPost]
public void UploadImage()
{
    if (Request.Files.Count > 0)
    {
        dynamic file = Request.Files[0];
        //do something with your 'file'
    }
}

这非常适合仅发送选定的文件。现在我的问题是我想将所有其他数据(模型类对象)也发送到相同的控制器方法。我也尝试使用json,但出现"非法调用"错误。

请指导我如何将两者传递到单一方法?如有任何疑问,请随时填写。帮助我,我在这一点上陷入困境。

谢谢。

我对您的

代码进行了测试,您唯一缺少的是将其他字段添加到您通过 AJAX 发送的 FormData 对象中。我的意思是像这样修改你的javascript代码:

var formData = new FormData();
var totalFiles = document.getElementById("fuUploadCV").files.length;
for (var i = 0; i < totalFiles; i++) {
   var file = document.getElementById("fuUploadCV").files[i];
   formData.append("FileUpload", file);
}
// This is what you are missing: adding the other form fields
var txtFirstName = $("#txtFirstName").val();
formData.append("txtFirstName", txtFirstName);
$.ajax({
    (... the rest of your code ...)

您需要将要发送到服务器的表单的每个值附加到服务器。

然后在服务器端,您可以通过以下方式访问字段,也可以基于当前代码

[HttpPost]
public void UploadImage()
{
   if (Request.Files.Count > 0)
   {
      dynamic file = Request.Files[0];
      //do something with your 'file'
      // This is the way to access your fields based on your code
      string txtFirstName = Request.Form["txtFirstName"];
      // do something with your fields
   }
}

我希望这有所帮助。