如何使用 Select 更改事件和 JQuery、Ajax 和 MVC 显示 PDF 文件

How to Display PDF File using Select Change Event with JQuery, Ajax and MVC

我正在使用 select 下拉菜单从我的 ASP.Net MVC 项目中的文件夹加载 pdf 文件,该项目运行顺利。我现在想要实现的是当用户从下拉列表中单击文件并加载它时加载 pdf 文件。我能够检索到一些需要的数据,但不确定如何继续使用 ajax 使其工作。任何指导将不胜感激。以下是我到目前为止所做的。

$(function () {
    $("#selectPdf").change(function () {

        var url = "Mechanical/Index";
        
        var fileid = $(this).find(":selected").val();
        var filename = $(this).find(":selected").text();

        
        $.ajax({
            url: url,

        Not sure how to proceed.    
        })
        

    });
});
<div class="pdfViewContainer">
    <div class="h3 card-header"><label id="pdfviewerlabel">Mechanical</label></div>
    <div id="pdfContainer" class="card-body">
        <div class="row mb-3">
            <div class="col-md-2">
                <form id="form" action="">
                    <select asp-for="FileId" asp-items="@Model.Files" id="selectPdf" class="form-control" datastyle="btn-warning">
                        <option disabled selected>-- Select File --</option>
                    </select>
                </form>
            </div>
        </div>
        <div id="pdf">
            <embed type="application/pdf" src="@Model.Path/@Model.Name" width="100%" height="1024px"/>
        </div>
    </div>
</div>

@section scripts {
    <script src="~/js/ShowPDF.js"></script>
}
namespace MyNamespace.Controllers
{
    public class MechanicalController : Controller
    {
        private readonly IWebHostEnvironment _webHostEnvironment;

        public MechanicalController(IWebHostEnvironment webHostEnvironment)
        {
            _webHostEnvironment = webHostEnvironment;
        }

        private string fileDirectory = SD.Mechanical_Path;

        public IActionResult Index()
        {
            
            string path = $"{_webHostEnvironment.WebRootPath}{fileDirectory}";
            int nId = 1;

            var userFile = new UserFile();
            userFile.Files = new List<SelectListItem>();

            foreach (string pdfPath in Directory.EnumerateFiles(path, "*.pdf"))
            {
                userFile.Files.Add(new SelectListItem
                {
                    Text = Path.GetFileName(pdfPath),
                    Value = nId.ToString()
                });

                nId++;
            }

            int listCount = userFile.Files.Count - 1;
            userFile.Name = userFile.Files[listCount].Text;
            userFile.Path = fileDirectory.Replace('\', '/');
            return View(userFile);
        }
    }   
}
@model MyNamespace.Models.UserFile

namespace MyNamespace.Models
{
    public class UserFile
    {
        public int FileId { get; set; }

        public string Name { get; set; }

        public string Path { get; set; }

        public List<SelectListItem> Files { get; set; }
    }
}

为了在ajax回发时渲染更新的html,默认情况下可以在success函数中使用.html()。可以看到。但是在您使用 embed 元素的场景中,它只能用 src 更新,但不能通过 ajax 显示更新后的 pdf。所以我建议使用 window.location.replace 可以向后端发送新请求并更新 pdf。

@model UserFile 
<div class="pdfViewContainer">
    <div class="h3 card-header"><label id="pdfviewerlabel">Mechanical</label></div>
    <div id="pdfContainer" class="card-body">
        <div class="row mb-3">
            <div class="col-md-2">
                <form id="form" action="">
                    <select asp-for="FileId" asp-items="@Model.Files" id="selectPdf" class="form-control" datastyle="btn-warning">
                        <option disabled selected>-- Select File --</option>
                    </select>
                </form>
            </div>
        </div>
        <div id="pdf">
            <embed type="application/pdf" src="@Model.Path/@Model.Name" width="100%" height="1024px"/>
        </div>
    </div>
</div>

@section scripts {
 <script>
    $(function () {
        $("#selectPdf").change(function () {

            var url = "/Mechanical/Index";     //remember add `/`
        
            var filename = $(this).find(":selected").text();
            window.location.replace(url+"?filename="+filename);

           // $('#pdfViewContainer').load(url+"?filename="+filename);
            //$.ajax({
            //    url: url+"?filename="+filename,
            //    method:"GET",
            //    success:function(res){
            //        $("#pdfViewContainer").html(res);
            //    }
            //})             
        });
    });
</script>
}

控制器:

public IActionResult Index(string filename)
{

    string path = $"{_webHostEnvironment.WebRootPath}{fileDirectory}";
    int nId = 1;

    var userFile = new UserFile();
    userFile.Files = new List<SelectListItem>();

    foreach (string pdfPath in Directory.EnumerateFiles(path, "*.pdf"))
    {
        userFile.Files.Add(new SelectListItem
        {
            Text = Path.GetFileName(pdfPath),
            Value = nId.ToString(),
            Selected = filename== Path.GetFileName(pdfPath)?true : false    //better to modify here...
        });

        nId++;
    }

    int listCount = userFile.Files.Count - 1;
    userFile.Name = userFile.Files[listCount].Text;
    userFile.Path = fileDirectory.Replace('\', '/');
    if(filename != null)       
    {
        userFile.Name = filename;     //add here....
    } 
    return View(userFile);
}