首页 > 解决方案 > 上传文件并重新加载相同的局部视图

问题描述

晚上好,

我正在尝试上传文件,当表单提交时,我只想重新加载模态 div 中的部分视图,而不是整个页面。我查看了许多其他帖子,他们建议使用 AJAX,但即使我使用了 AJAX,也不仅仅是重新加载部分视图弹出窗口,而是将我带到部分视图的完整页面视图。我只想重新加载模态 div 内的内容。

这是我的代码:

控制器

 public PartialViewResult FileUpload(int jobID)
    {
        ViewBag.jobID = jobID;
        return PartialView(GetFiles(jobID));
    }

    [HttpPost]
    public ActionResult FileUpload(int jobID, HttpPostedFileBase files)
    {

        int id = Convert.ToInt32(Session["id"]);
        String FileExt = Path.GetExtension(files.FileName).ToUpper();

        if(FileExt == ".PDF")
        { 
            Stream str = files.InputStream;
            BinaryReader Br = new BinaryReader(str);
            Byte[] FileDet = Br.ReadBytes((Int32)str.Length);
            UploadFileModel Fd = new UploadFileModel();
            Fd.FileName = files.FileName;
            Fd.FileContent = FileDet;
            Fd.personID = id;
            Fd.jobID = jobID;

            file fileDB = new file();
            fileDB.FileContent = Fd.FileContent;
            fileDB.FileName = Fd.FileName;
            fileDB.personID = id;
            fileDB.jobID = Fd.jobID;
            db.files.Add(fileDB);
            db.SaveChanges();
            return PartialView("FileUpload", GetFiles(jobID));
        }
        else
        {
            ViewBag.FileStatus = "Invalid file format.";
            return PartialView();
        }
        

        

    }
    [HttpPost]
    public FileResult DownloadFile(int? fileId)
    {
        byte[] bytes;
        string fileName, contentType;
        var file = db.files.Find(fileId);
        bytes = (byte[])file.FileContent;
        fileName = file.FileName;

        return File(bytes, fileName);
    }

    public List<UploadFileModel> GetFiles(int jobID)
    {
        List<UploadFileModel> files = new List<UploadFileModel>();
        var filesDB = db.files.Where(x => x.jobID == jobID);
        foreach (var fileDB in filesDB)
        {
            files.Add(new UploadFileModel
            {
                id = fileDB.id,
                FileName = fileDB.FileName,
                personID = fileDB.personID,
                jobID = fileDB.jobID
            });
            
        }
        return files;
    }

局部视图:

@model  IEnumerable<Church_Musician_Administration_App__Updated_.Models.UploadFileModel>
<style>
    .table-striped tbody tr:nth-of-type(odd) {
        background-color: rgb(222, 178, 241);
    }

    .table-striped tbody tr:nth-of-type(even) {
        background-color: rgb(233, 204, 246);
    }

    #fileTable {
        font-family: "Arial";
    }

        #fileTable tr {
            cursor: default;
        }

    a:link {
        color: darkviolet;
        background-color: transparent;
        text-decoration: none;
    }

    a:visited {
        color: gray;
        background-color: transparent;
        text-decoration: none;
    }

    a:hover {
        color: white;
        background-color: transparent;
        text-decoration: none;
    }

    a:active {
        color: rebeccapurple;
        background-color: transparent;
        text-decoration: none;
    }
</style>
@using (Html.BeginForm("FileUpload", "App", FormMethod.Post, new { enctype = "multipart/form-data", id="fileUploadForm"}))
{
    <input type="hidden" name="jobID" value="@ViewBag.jobID" />
    <label class="btn btn-primary" for="my-file-selector">
        <input id="my-file-selector" name="files" type="file" style="display:none"
               onchange="$('#upload-file-info').text(this.files[0].name)">
        Choose File
    </label>
    <span class='label label-info' id="upload-file-info">No File Uploaded</span>

    <input class="btn btn-primary" type="submit" id="btnUpload" value="Upload" style="margin-bottom:5px" />
}

@using (Html.BeginForm("DownloadFile", "App", FormMethod.Post))
{
    <input type="hidden" id="hfFileId" name="FileId" />
    <input type="submit" id="btnDownload" value="Download" style="display:none" />
}
<hr />

<table id="fileTable" class="table table-striped" style="width:100%; border: 1px solid rgba(0,0,0,.125); border-left:none; border-right:none; text-align: center; display:inline-table;">
    <tbody>
        <tr style="background-color:darkviolet; height:40px; width:100%">
            <th style="display:none;">JobID</th>
            <th style="display:none">File ID</th>
            <th style="color:white; border: 1px solid rgba(0,0,0,.125);">File Name</th>
            <th style="color:white; border: 1px solid rgba(0,0,0,.125);">Download</th>
        </tr>
        @if (Model.Count() > 0)
        {
            foreach (var file in Model)
            {
                <tr>
                    <td style="display:none;">@file.id</td>
                    <td style="border: 1px solid rgba(0,0,0,.125);">@file.FileName</td>
                    <td style="border: 1px solid rgba(0,0,0,.125);"><a href="javascript:;" onclick="DownloadFile(@file.id)">Download</a></td>
                </tr>
            }
        }
        else
        {
            <tr>
                <td colspan="3">&nbsp;</td>
            </tr>
        }
    </tbody>
</table>

<script type="text/javascript">
    function DownloadFile(fileId) {
        $("#hfFileId").val(fileId);
        $("#btnDownload")[0].click();
    };
</script>
<script>
    $('#btnUpload').click(function (event) {
        event.preventDefault();
        event.stopImmediatePropagation();
        $('#fileUploadForm').submit();

        $.ajax({
            url: '/App/FileUpload',
            type: 'POST',
            success: function (data) {
                $("#addMusicModalBodyDiv").html(data);
                $("#addMusicModal").modal("show");
            }
        });
    });
</script>

编辑:这是定义 addMusicModal 的代码。它位于一个名为 ViewSubstituteJobs 的视图中

<button type="button" class="btn btn-primary" id="addMusic" onclick="addMusic()">Add Music</button>

<div class="modal" tabindex="-1" id="addMusicModal">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Add Music</h5>
                <button type="button" class="close" aria-label="Close" id="closeAddMusicModal" onclick="closeDialog()">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body" id="addMusicModalBodyDiv">

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

var addMusic = function () {
        var idFromTable = $("#subJobs tr").closest('tr.highlight').find('td:eq(0)').text();
        if (idFromTable == 0) {
            return false;
        }

        $.ajax({

            type: "GET",
            url: "/App/FileUpload",
            data: {
                jobID: idFromTable,
            },
            success: function (response) {
                $(".modal").modal("hide");
                $("#addMusicModalBodyDiv").html(response);
                $("#addMusicModal").modal("show");
            }
        })
    }
</script>

标签: c#jqueryfile-upload

解决方案


推荐阅读