Search code examples
javascriptc#ajaxasp.net-coremultipartform-data

send FormData with two files and text to controller


I am trying to send a FormData object which has some text fields, an image file and a pdf file to a action in controller. But at no cost it sending the form data to action. Debugging in browser doesn't show any error or anything. Please guide what am i missing or doing wrong.

The html

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

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

    //console.log(formData);
    $.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 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");
    }
}

Here is the Model

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

Solution

  • Based on your code, it seems that you'd like to make a AJAX request to upload files with other data to ASP.NET Core Razor pages handler method.

    To achieve it, you can try to modify the code as below.

    In Upload.cshtml

    <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>
    @Html.AntiForgeryToken()
    
    @section scripts{
        <script>
            function uploadbookfunc() {
                //prevent it from submitting the form
                event.preventDefault();
    
                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);
    
                //console.log(formData);
                $.ajax({
                    url: "/Upload?handler=BookUpload",
                    type: 'POST',
                    headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
                    contentType: false,
                    processData: false,
                    data: formData,
                    success: function (response) {
                        alert(response);
                    },
                    failure: function (response) {
                        alert('failed');
                    }
                });
    
            }
        </script>
    }
    

    In Upload.cshtml.cs

    public class UploadModel : PageModel
    {
        [BindProperty]
        public UploadBook uploadBook { get; set; }
        public void OnGet()
        {
        }
    
        public IActionResult OnPostBookUpload()
        {
            //code logic here
            var title = uploadBook.Title;
            //...
    
            return new JsonResult("Success");
        }
    }
    

    Test Result

    enter image description here