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