通过ajax mvc上传文件HttpPostedFileBase时返回null

时间:2019-11-08 07:29:54

标签: jquery ajax model-view-controller jsonresult

我正在尝试通过AJAX请求将文件和一些数据上传到控制器操作,但是HttpPostedFileBase参数始终为空

这是我的cshtml

const Test = 'foo';
const Action = 'bar';
const Nothing = 'baz';

const array1Values = [{name: Test}, {name:Action}];
const array2 = [{Id: 1, Status: Test}, {Id:2, Status: Test}, {Id:3, Status: Test}, {Id:4, Status: Action}, {Id:5, Status: Nothing}];

const names = new Set(array1Values.map(val => val.name));
const matchingItemsInArr2 = array2
  .filter(({ Status }) => names.has(Status));
  
console.log(matchingItemsInArr2);

这是我的控制器

<div class="modal fade" id="MyModal">
                    <div class="modal-dialog">
                        <div class="modal-content">
                            <div class="modal-header">
                                <a href="#" class="close" data- 
    dismiss="modal">&times;</a>
                                <h4 id="ModalTitle"></h4>
                            </div>
                            <div class="modal-body">
                                @using (Html.BeginForm("EditResearch", 
    "Admin", FormMethod.Post, new { id = "form", enctype = "multipart/form- 
    data" }))
                                    {


                                    @Html.AntiForgeryToken()

                                    <fieldset id="SubmitForm">
                                        @Html.HiddenFor(m => m.ResearchID, 
    new { @id = "ResearchID" })


                                        <div class="input-field">
                                            <label for="name">Journal Name     </label>
                                        </div>
                                        <div class="form-group">
                                            @Html.TextBoxFor(m => 
    m.NameJournal, new { @id = "NameJournal", @class = "form-control", 
    @placeholder = "Journal Name*" })
                                        </div>

                                        <div class="input-field">
                                            <label for="name">File</label>
                                        </div>
                                        <div class="form-group">
                                            @Html.TextBoxFor(model =>     model.ResearchFile, new { @type = "file", @name = "ResearchFile", @id
= 
    "ResearchFile" })

                                            @*<input name="fileresearch" 
    id="fileresearch" type="file" />*@
                                        </div>

                                        <div class="input-field">
                                            <label for="name">
                                                Abstract
                                            </label>
                                        </div>
                                        <div class="form-group">
                                            @Html.TextAreaFor(model => 
    model.ResearchContents, new { @id = "ResearchContents", @class = "form-     control", @onKeyUp = "Count(this,1000)", @onChange = "Count(this,1000)",     placeholder = "Abstract", name = "name", rows
= "6", cols = "85" })
                                        </div>



                                        <div class="form-group">
                                            <a href="#" class="btn btn-block 
    btn-danger" id="SaveStudentRecord">Save</a>
                                        </div>

                                    </fieldset>

                                }
                            </div>
                        </div>
                    </div>
                </div>

    $("#SaveStudentRecord").click(function () {
                        var data = $("#SubmitForm").serialize();

                        $.ajax({
                            type: "Post",
                            url: "/Admin/SaveDataInDatabase",
                            data: data,
                            //contentType: false,
                            //processData: false,
                            success: function (result) {

                                if (result) {
                                    alert("Done.");
                                    window.location.href = 
    "/Admin/EditResearch";
                                    $("#MyModal").modal("hide");
                                }
                                else {
                                    alert("Fill Boxes");
                                    //window.location.href = 
    "/Admin/EditResearch";
                                    //$("#MyModal").modal("hide");
                                }



                            }
                        })
                    })

这是我的课程ResearchModel

[HttpPost]
        public JsonResult SaveDataInDatabase(ResearchBL model, 
    HttpPostedFileBase ResearchFile)
        {
            try
            {

                if (Session["user"] != null)
                {
                    ViewBag.Message = "";
                    string Err = "";
                    string userID = Session["user"].ToString();

                    ResearchModel researchObj = new ResearchModel();

                    bool Check = researchObj.SaveDataInDatabase(model, 
    userID, ResearchFile, ref Err);

                    ViewBag.Message = Err;

                    return Json(Check, JsonRequestBehavior.AllowGet);

                }
                else
                {
                    RedirectToAction("Login", "Admin");
                    return null;
                }

            }
            catch (Exception ex)
            {
                return null;
            }

        }

3 个答案:

答案 0 :(得分:0)

Ajax不会使用Direct表单来完成它。Submit将接收数据。 在@BeginForm或标签下编写表单,然后使用按钮类型进行按钮

答案 1 :(得分:0)

我认为您可以将Form的另一个文件附加为FormData。

例如:

exports

,并在控制器中执行此操作。.以Request.Form的形式访问数据     例如

var files = $("#FileUpload").get(0).files;//file which you are uploading...
            var fileData = new FormData();
            for (var i = 0; i < files.length; i++) {
                fileData.append("FileUpload", files[i]);
                fileData.append("DocId", $("#SelectedDocId").val());
            }
            $.ajax({
                type: "POST",
                url: '//',your url i.e/Controller/Action
                dataType: "json",
                autoUpload: false,
                contentType: false, // Not to set any content header
                processData: false, // Not to process data
                data: fileData,
                success: function (result, status, xhr) {
                //Success....
                }   

答案 2 :(得分:0)

您应在文件后附加FormData。 这可能会对您有所帮助。

 var formData = new FormData();        
            var file = document.getElementById("FileUpload").files[0];
            formData.append("Image", file);
      $.ajax({
                    type: "POST",
                    url: '@Url.Action("SaveDataInDatabase", "Admin")',
                    contentType: false,
                    processData: false,
                    data: formData,
                    dataType: 'json',
                    success: function (resp) {

                    },                
                    error: function (jqXHR, exception) {
                        if (jqXHR.status === 0) {
                            alert('Not connect.\n Verify Network.');
                        } else if (jqXHR.status == 404) {
                            alert('Requested page found. [404]');
                        } else if (jqXHR.status == 500) {
                            alert('Internal Server Error [500]');
                        } else if (exception === 'parsererror') {
                            alert('Requested JSON parse failed.');
                        } else if (exception === 'timeout') {
                            alert('Time out error.');
                        } else if (exception === 'abort') {
                            alert('Ajax request aborted.');
                        } else {
                            alert('Uncaught Error.\n' + jqXHR.responseText);
                        }
                    }
                });