transmit FormData containing two files and a text message to the controller

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

Answer №1

From the code provided, it appears that you are trying to implement an AJAX request to upload files along with other data to an ASP.NET Core Razor pages handler method.

To achieve this functionality, you can make the following modifications in your code.

Update Upload.cshtml as follows:

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

            $.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 file:

public class UploadModel : PageModel
{
    [BindProperty]
    public UploadBook uploadBook { get; set; }
    public void OnGet()
    {
    }

    public IActionResult OnPostBookUpload()
    {
        //Add your logic here
        var title = uploadBook.Title;
        //...

        return new JsonResult("Success");
    }
}

Test Result

https://i.sstatic.net/dTevs.png

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I am able to successfully receive accurate data in JSON format, however I am facing difficulties binding it to a jquery

I am struggling with integrating data fetched in JSON format using $.ajax into a table using jquery's datatable. Below is the JavaScript code I have been trying: $(document).ready(function () { $.ajax({ type: "POST", url: "Result.aspx/getUser ...

Create a div element that initially aligns to the left, expands to the full width of the window, and then shrinks back

Hi there! I am currently diving into the world of javascript and jQuery, with a specific goal in mind. I want to create functionality where a div expands to the width of the window when clicked, then shrinks back down to its original size but switches alig ...

Grids designed in the style of Pinterest

Seeking advice on aligning divs in a Pinterest-style layout. Currently, my setup looks like this: https://i.sstatic.net/erlho.png But I want it to look more like this: https://i.sstatic.net/K9FnD.png Would greatly appreciate any tips or suggestions on ho ...

Challenges with NPM testing

Are there any reported issues with npm on Ubuntu 18.04? Or are there known solutions to the 100:1 error? I am currently enrolled in a course and it's crucial for me to be able to execute code using npm test. Despite multiple attempts at deleting and ...

Searching in binary for the number closest to the target float value

Seeking assistance with a float array conundrum! I am trying to identify the closest float value to a target number within the array. My attempt involved utilizing a basic binary search algorithm in JavaScript, but I've hit a roadblock. function bina ...

CSS navbar with a unique design: Issue with List Hover not Persisting

I'm facing a common issue with a pure CSS navbar. I have constructed a navbar using ul and li elements, but I am unable to make the menus stay visible when I hover over them. The problem lies in the fact that the menu opens only when I hover over the ...

The Express server is failing to deliver a response to the client when using the fetch method

Currently, I am utilizing express for the server side of my project. To send a post request from the client to the server, I am using fetch. The data that I am sending to the server is being successfully transmitted and displayed. However, I am encounteri ...

Utilizing the jQuery plugin 'cookie' to retain the current tab selection on a webpage

Is it possible to provide a detailed explanation on how I can utilize the jQuery Cookie plugin to maintain the selected tab throughout my entire website? Here is the current JavaScript code in JSFiddle format: http://jsfiddle.net/mcgarriers/RXkyC/ Even i ...

Interactive pop-up messages created with CSS and JavaScript that appear and fade based on the URL query string

I have a referral form on this page that I want people to use repeatedly. After submitting the form, it reloads the page with the query string ?referralsent=true so users can refer more people through the form. However, I also want to show users a confir ...

The issue arises with proptypes validation while implementing material-ui components

Just embarked on a new ReactJS project and ran into a plethora of errors when I integrated material-ui. One of the errors looked like this: bundle.js:12441 Warning: Failed Context Types: Calling PropTypes validators directly is not supported by the prop ...

Putting a Pause on CSS Transition using jQuery

I am attempting to delay a CSS transition for an element by using a delay function, with an additional 0.2s applied to make it slide 0.2s later than the initial delay of the main wrapper. I am applying a class to give it a transition effect to slide from r ...

Cookies are failing to be saved upon reloading the page

I found this snippet of code $(document).ready(function () { var d = new Date(); var newMinutes = d.getTimezoneOffset(); var storedMinutes = getCookieValue("tzom"); if (newMinutes != storedMinutes) { setCookie("tzom", newMinutes) ...

What is the best practice for adding a DOM element at a precise location within an ng-repeat loop?

I am currently working on developing a podcast player application using AngularJS. At this point, I have successfully created a list of available podcasts that can be played, utilizing ng-repeat. The code for the list is shown below: <ul ng-controller ...

Enhancing the building matrix with JavaScript (or jQuery)

I have created a custom Javascript function for extracting specific data from a matrix. The main purpose of the function is to retrieve data based on dates within a given range. Here's how it works: The matrix[0][i] stores date values I need to extr ...

jQuery problem: Unable to access a property that is undefined

After testing my code on JSfiddle, I noticed that it works perfectly. However, when I try to implement it on a webpage with jQuery already loaded in the DOM, I encounter a console error, shown in the screenshot. I am certain that the iframe selector I am ...

What about numerical inputs lacking spinners?

Is there a more efficient way for users to input a decimal number like 64.32, and have it be two-way-bound to a property of type number? I attempted to use <input type="number" [(ngModel)]="size"> However, this displays a spinner which isn't ...

Transform the image data for display in a web browser

Attempting to retrieve an encrypted image file from Amazon S3 using a presigned link with AJAX is resulting in a jumble of gibberish image data. $(document).on 'click', '.js-download', (event) -> event.preventDefault() $.ajax t ...

Issues arise when using the select element

Struggling with submitting my list of items from a select in AngularJS. This is my first time posting here and I'm still finding my way around. The issue lies in using ng-repeat in my HTML to display all items. When the screen loads, it only shows: { ...

Phonegap: Displaying audio controls and metadata for my audio stream on the lock screen and in the drop-down status bar

After successfully creating my initial android app for phonegap 5.1 that plays an audio stream, I am currently facing an issue. I am unable to locate any solutions: How can I display audio controls and metadata of my audio stream on the lock screen as well ...

Retrieve JSON object based on its unique identifier from a different JSON file

I am working with 2 API resources: and it returns JSON data like this: { "id": 771, "title": "Call to Alyce Herman - Engine Assembler", "assigned_with_person_id": 317, } provides ...