I have encountered an issue while trying to send a FormData object containing text fields, an image file, and a PDF file to an action in the controller. Despite my efforts, the form data is not being sent to the action. I have checked for errors through browser debugging but no specific error or issue is displayed. Could you please provide guidance on what might be missing or incorrectly done?
Below is the HTML code:
<form>
<input type="text" id="title" placeholder="Title" />
<br />
<br />
<input type="text" id="auth" placeholder="Author" />
<br />
<br />
<input type="text" id="dept" placeholder="Department" />
<br />
<br />
<input type="text" id="price" placeholder="Price" />
<br />
<br />
<input type="text" id="year" placeholder="Year published" />
<br />
<br />
<label for="jpg">Select JPEG for Cover photo</label>
<input type="file" id="jpg" />
<br />
<br />
<label for="pdf">Select PDF</label>
<input type="file" id="pdf" />
<br />
<br />
<button type="submit" onclick="uploadbookfunc()">Submit</button>
</form>
Here is the associated JavaScript function:
function uploadbookfunc() {
var title = document.getElementById("title").value;
var author = document.getElementById("auth").value;
var department = document.getElementById("dept").value;
var price = document.getElementById("price").value;
var yearpub = document.getElementById("year").value;
const img = document.getElementById('jpg').files[0];
const pdffile = document.getElementById('pdf').files[0];
var formData = new FormData();
formData.append("Title", title);
formData.append("Author", author);
formData.append("Department", department);
formData.append("Price", price);
formData.append("YearPublished", yearpub);
formData.append("ImageFile", img);
formData.append("PdfFile", pdffile);
$.ajax({
url: "/Upload?handler=BookUpload",
type: 'POST',
contentType: false,
processData: false,
data: formData,
success: function (response) {
alert(response);
},
failure: function (response) {
alert('failed');
}
});
}
Here is the relevant Action method:
public class UploadModel : PageModel
{
public void OnGet()
{
}
public IActionResult OnPostBookUpload()
{
MemoryStream stream = new MemoryStream();
Request.Body.CopyTo(stream);
stream.Position = 0;
using (StreamReader reader = new StreamReader(stream))
{
string requestBody = reader.ReadToEnd();
// Write to database.....
}
return new JsonResult("Success");
}
}
This is the Model structure used:
public class UploadBook
{
public string Id { get; set; }
public string Title { get; set; }
public string Author { get; set; }
public string Department { get; set; }
public double Price { get; set; }
public int YearPublished { get; set; }
public IFormFile ImageFile { get; set; }
public IFormFile PdfFile { get; set; }
}