1

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 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; }
    }
}
Rena
  • 30,832
  • 6
  • 37
  • 72
user3596617
  • 83
  • 2
  • 9
  • Not sure ? just try : https://api.jquery.com/jquery.ajax/ and then come back if you get really stuck – SKJ Mar 10 '22 at 22:06

1 Answers1

0

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

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);
}
Rena
  • 30,832
  • 6
  • 37
  • 72