Home > Back-end >  How to Display PDF File using Select Change Event with JQuery, Ajax and MVC
How to Display PDF File using Select Change Event with JQuery, Ajax and MVC

Time:03-12

I’m using a select dropdown to load pdf files from a folder in my ASP.Net MVC project which works without a hitch. What I’m trying to achieve now is to load a pdf file when a user clicks on a file from the dropdown and load it. I’m able to retrieve some of the needed data but am unsure on how to proceed to make it work using ajax. Any guidance would be much appreciated. Below is what I have done so far.

$(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 >
    <div ><label id="pdfviewerlabel">Mechanical</label></div>
    <div id="pdfContainer" >
        <div >
            <div >
                <form id="form" action="">
                    <select asp-for="FileId" asp-items="@Model.Files" id="selectPdf"  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; }
    }
}

CodePudding user response:

For rendering the updated html when ajax postback, you can use .html() in success function by default. You can see a simple example here. But in your scenario you use embed element, it can only be updated with src but cannot display the updated pdf by ajax. So I suggest use window.location.replace which can send a new request to backend and update the pdf.

@model UserFile 
<div >
    <div ><label id="pdfviewerlabel">Mechanical</label></div>
    <div id="pdfContainer" >
        <div >
            <div >
                <form id="form" action="">
                    <select asp-for="FileId" asp-items="@Model.Files" id="selectPdf"  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>
}

Controller:

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);
}
  • Related