Tips for creating a fetch call to send data to a function that requires an Object parameter?

I'm facing some issues with using a fetch post call to pass an object to a method that expects the object. I've created a payload and passed it, but it doesn't seem to be working as expected. I set a breakpoint in the code behind, but it's never triggered. I'm unsure why the fetch call is not functioning properly. Any suggestions on why the endpoint might not be getting reached?

This is my C# method:

    [HttpPost]
    [Route("ResetPassword")]
    private void ResetPassword(Player player) {

   }

Javascript:

const continueBtn = document.getElementById("continueBtn");
continueBtn.onclick = () => {
const email = document.getElementById("lblEmail").innerHTML;
sendResetEmail(email);
}

async function sendResetEmail(email) {
const payload = {
    email: email
}

const data = new FormData();
data.append("json", JSON.stringify(payload));

let sendResetEmail = await fetch(`/ResetPassword`,
    {
        method: 'POST',
        body: data
    });
}

Answer №1

If you prefer not to specify the parameter name in your client, you must include the [FromBody] attribute in your API endpoint:

[HttpPost]
[Route("ResetPassword")]
private void ResetPassword([FromBody] Player player){
}

As for the client side, there are various approaches, but the most commonly used method is JSON encoding:

const payload = {
    email: email
}

const data = JSON.stringify(payload);

let sendResetEmail = await fetch(`/ResetPassword`,
    {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: data
    });
}

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

Swap the Text for a Button

I've been searching for a solution to this problem, but all I seem to find online is advice on how to "replace button text." What I'm trying to achieve is to have text change into a button when hovered over. I've attempted using fadeIn/fade ...

Reposition HTML elements using JavaScript

Is there a way to use JavaScript or jQuery to replace the image with class "fnone" located under the span element with class "ddlabel"? <span id="flat_title" class="ddTitleText "> <img class="fnone" src="images/pinc.png"> <span ...

Delete the initial image from the opening list item using jQuery

Here is an example of some HTML code: <ul class="products"> <li> <a href="#" class="product-images"> <span class="featured-image"> <img src="img1.jpg"/> <img src="img ...

Unveiling the dependencies loaded by each assembly during runtime

Is there an efficient method to identify the assembly responsible for triggering specific dependencies to load at runtime? I am dealing with a situation where an outdated assembly is referenced somewhere among the 100+ assemblies that are loaded as part of ...

Utilizing the "return" keyword in Javascript outside of function declarations

Exploring the Impact of Using the Return Keyword in JavaScript Scripts Beyond Functions in Browsers and Node.js Recently, I experimented with utilizing the return keyword in a Node.js script like so: #!/usr/bin/env node return 10; My initial assumption ...

Attempting to load the parent window of a framed page from a separate domain results in a permission denial issue in Internet

Having an issue with a login page that is hosted within an iframe on a different domain. After a successful login, I am attempting to load the following page: <html> <head> </head> <body onload="parent.window.loca ...

"Encountering a 404 Not Found error while using Next.js and React-Query

I am currently facing a problem with setting up my Next.js project alongside an Express.js back-end. Initially, I set up the back-end as a regular one based on the documentation provided by Next.js. However, I am unsure if this approach is correct. My issu ...

AngularJS Router and .NET backend - troubleshooting templateUrl redirections

I am currently working on developing an Angular application that utilizes $routeProvider. The backend of the application is built using .NET, which serves HTML files tailored with specific permissions and roles for my app. Occasionally, when a certain acti ...

Ways to guide user after logging out

My Angular front end includes the following code in app.js to handle user logout: .when('/logout', { templateUrl: 'mysite/views/logout.html', resolve: { authenticated: ['djangoAuth', function(djangoAuth){ return ...

The jQuery method .on gathers and retains click events

I created a component that manages a view containing articles with games. In order to prevent memory overload and optimize performance, I implemented a solution where when a user clicks on an article (each having the class "flashgame"), they can choose to ...

Alter the browser's URI without having to reload the page

Is there a way to change the browser URL (or URI) without refreshing the page using HTML5 and HTML5Shiv for IE? For example, if I am currently on http://www.example.com but want to transition to http://www.example.com/4f6gt without the need for a full pa ...

Executing MySQL queries synchronously in Node.js

When working with NodeJS and mysql2 to save data in a database, there are times when I need to perform database saves synchronously. An example of this is below: if(rent.client.id === 0){ //Save client connection.query('INSERT INTO clients (n ...

I am interested in checking the dates of the current date and disabling the button if the date falls within that range

I am attempting to deactivate a button if the current date falls within a three-month period. Despite my efforts to use a combination of Php and JavaScript, I was unable to make it work. PHP Code @php($found = false) @foreach($doctors as $doctor) ...

Using jQuery to animate based on scrolling to a specific location

Currently, I am working on a smooth scroll effect where an element's top padding reduces gradually as the user scrolls. Simultaneously, I want two child elements to fade - one fading out and the other fading in. While I have achieved the fading effect ...

Attempting to use express and nodemailer to send an email, but there is absolutely no output appearing in either the console or the terminal

When I click the send email button, it should send the data to a mailhog inbox. However, nothing happens - no errors in the console or terminal. My goal is to use nodemailer to send the name, email, chosen plan, and message from the form to the mailhog add ...

Control the HTML button's state according to the information received from the server

I am currently working with datatable Jquery and using an ajax call to retrieve data from the server. Let's assume that the database consists of three attributes: "Attribute1, Attribute2, Status". Depending on the Status attribute, I need to enable or ...

Implementing jQuery validation on tab key press

Is it possible to implement field validation in JSP while tabbing through the fields using jQuery? Here is a snippet of my JSP page: <form:form method="POST" commandName="test" name="testname" onclick="submitForm();" > <div> <form:inpu ...

Maintain daily data that can be updated in JSON format

I'm working on a web application that utilizes client-side MVC with backbone.js and Spring on the server side. I have a scenario where I require data that needs to be updated daily or every couple of days. The data will be used on the client side for ...

Implementing various event listeners for asynchronous JavaScript and XML requests (

Struggling to iterate through an ajax query and encountering a problem where the i value always defaults to 1. I'm not very well-versed in js so any suggestions on how to tackle this issue or possibly a better approach would be greatly appreciated. Th ...

Switching left navigation in material-ui when the user interacts within the application boundary

I am currently implementing a toggle feature in my AppBar to display the LeftNav. I have successfully set it up to close when the toggle is clicked again. However, I wish to mimic the behavior of most left nav bars where clicking anywhere outside of the ...