когда выгрузка файла HttpPostedFileBase через ajax mvc возвращает ноль - PullRequest
1 голос
/ 08 ноября 2019

Я пытаюсь загрузить файл и некоторые данные в действие контроллера через запрос AJAX, однако параметр HttpPostedFileBase всегда равен нулю

, вот мой cshtml

<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");
                                }



                            }
                        })
                    })

вот мой контроллер

[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;
            }

        }

вот мой класс ResearchModel

    public Boolean SaveDataInDatabase(ResearchBL model, string userID, 
    HttpPostedFileBase ResearchFile, ref string Err)
            {
                var result = false;

                    using (ZUNew1Entities2 db = new ZUNew1Entities2())
                    {
                        if (model.ResearchID > 0)
                        {

                            if (!string.IsNullOrEmpty(model.ResearcherName)
                            && !string.IsNullOrEmpty(model.ResearchName)
                            && !string.IsNullOrEmpty(model.NameJournal)
                            && !string.IsNullOrEmpty(model.ResearchContents)
                            && !string.IsNullOrEmpty(model.VolumeNumber)

                            )
                            {
                                Research research = 
    db.Researches.SingleOrDefault(x => x.IsDeleted == false && x.ResearchID 
    == 
    model.ResearchID);

                                research.ResearchName = model.ResearchName;
                                research.ResearcherName = 
    model.ResearcherName;
                                research.NameJournal = model.NameJournal;
                                research.VolumeNumber = model.VolumeNumber;
                                research.ResearchContents = 
    model.ResearchContents;

                                string day = "01";
                                string cal = model.DateOfPublication + "-" + 
    day;

                                research.DateOfPublication = 
    Convert.ToDateTime(cal);


                                // Update Research File 
    ****************************

                                string File;

                                string uploadFile = 
    "~/UploadFile/Researcher/Files/";

                                if (model.ResearchFile != null)
                                {

                                    var fileName = 
    Path.GetFileName(ResearchFile.FileName);
                                    string pathURL = uploadFile + userID + 
    "_" + DateTime.Now.Hour.ToString() + "_" + 
    DateTime.Now.Minute.ToString() + 
    "_" + DateTime.Now.Second.ToString() + 
    DateTime.Now.Millisecond.ToString() + 
    ".pdf";

                                    var path = 
    Path.Combine(System.Web.HttpContext.Current.Server.MapPath(pathURL));
                                    ResearchFile.SaveAs(path);


                                }
                                else
                                {

                                    research.ResearchFile = null;

                                }


                                db.Entry(research).State = 
                EntityState.Modified;
                                db.SaveChanges();
                                result = true;
                                Err = "";
                                return true;

                            }
                            else
                            {

                                Err = "Fill Boxes !!";
                                return false;

                            }

                        }
                        else
                        {

                            Err = "";
                            result = false;
                            return false;

                        }
                    }

            }

1 Ответ

0 голосов
/ 09 ноября 2019

Ajax не будет использовать прямую форму для отправки данных. Напишите свою форму под @BeginForm или тегом и используйте тип кнопки для кнопки

...