Upon clicking the button, the system triggers an update to the database

I am currently working on an interface that involves buttons for updating a database. For example, I have a variable named "Estado" which is initially set as "emAvaliacao". When the button "Aceite" is clicked, the value of "Estado" changes to "Aceite".

The following functions are used in this process:

function updateDatabase(markerId, newState) {
    $.ajax
        ({
            url: `/api/IgnicoesAPI/${markerId}`,
            type: 'PUT',
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify({
                Id: +markerId,
                Estado: newState
            }),
            success: function (result) {
                 connection.invoke("PostMarker").catch(function (err) {
                              return console.error(err.toString());
                });
            },
            error: function () {
                alert("An error occurred!");
            }
        });
}

Below is the PUT function:

[HttpPut("{id}")]
public async Task<IActionResult> UpdateIgnicoes([FromRoute] int id, [FromBody] Ignicoes ignicao)
{
        
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

    if (id != ignicao.Id)
    {
        return BadRequest();
    }

    var decisionDate = DateTime.Now;
    var ig = _context.Ignicoes.FirstOrDefault(ignicaoId => ignicaoId.Id.Equals(id));
    
    if (ig != null)
    {
        ig.Estado = ignicao.Estado;              
        ig.DataDecisaoIgnicao = decisionDate;
    }
    
    try
    {
        await _context.SaveChangesAsync();
    }
    catch (DbUpdateConcurrencyException)
    {
        if (!IgnicoesExists(id))
        {
            return NotFound();
        }
        else
        {
            throw;
        }
    }

    return NoContent();
}

Currently, I am facing a 400 error and need assistance in resolving it. Can anyone provide guidance on how to tackle this issue?

Answer №1

To identify the specific line causing the exception, consider utilizing Debug.

  1. Ensure that the url you are posting routes to your PutIgnicoes action.

    The correct attribute route

    [HttpPut("~/api/IgnicoesAPI/{id}")]
    is not evident in the posted code.

  2. Verify the parameters being passed to the action.

Data: JSON.stringify({ Id: +idmarcador, Estado: novoEstado }),

public async Task<IActionResult> PutIgnicoes([FromRoute] int id, [FromBody] Ignicoes ignicao)

Answer №2

The root of Error 400 typically lies in the return BadRequest(); within your action code. It is essential to troubleshoot and inspect the payload to ensure that the data can successfully bind to the Ignicoes model.

If issues persist, kindly provide us with a glimpse of the Ignicoes class and the request payload for further analysis.

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

What is causing my AJAX script to refresh the page repeatedly?

I am currently testing the functionality of submitting a form using ajax. The script I have in place is designed to echo some plain text in processform.php. However, when I click on the submit button, no alert is displayed and the page is reloaded instead. ...

Styling the background position in CSS with the :target pseudo-class

After conducting some research, I was unable to find a satisfactory answer to my question. Essentially, I am attempting to shrink my website's header when a button is clicked. Here is the CSS code: I have been experimenting with making the backgrou ...

There is an issue with Node/Express not accurately updating the data model

I recently went through a tutorial on creating a RESTful API with Node.js and MongoDB. While it worked well overall, I encountered a few issues. My Player model is as follows: var player = new mongoose.Schema({ name: String, email: String, score: String } ...

Can you explain the distinct variations between these two approaches for obtaining API data?

When working with third-party APIs in NextJS 14, I encountered two different methods to query the API that resulted in slightly different outcomes. Method 1: Located within the /api folder as a route handler: export async function GET() { const res = aw ...

What is the most efficient way to display the state immediately after updating it?

Introduction: My journey with ReactJS is just beginning, having started only a week ago. While I may be new to this, I am determined to learn and improve. So, please feel free to critique my work and provide feedback even if it may be harsh. Abstract: Cur ...

Responsive Website with Horizontal Scrolling

Is it feasible to develop a website that smoothly scrolls across five panels horizontally while maintaining responsiveness? I've managed to achieve this for a specific viewport size by nesting a div with the five panels extended and using javascript t ...

Some images fail to load on Ember in the production environment

I am facing an issue with my Ember-cli 1.13 application where all images are loading correctly except those in a specific component. The component is named "list-item" and is defined as follows: {{list-item url="list-url" name="List Name" price="240"}} I ...

Using SqlBulkCopy to transfer data from a CSV file to a SQL Server is an

I'm facing a challenge with a function that creates a table and imports a CSV File. The problem arises when the CSV File does not have an ID column initially, causing errors when trying to send the data to the database. To address this, I attempted to ...

The JavaScript array created from parsing JSON returns a value of undefined

Once again, the gecko scenario! The JSON used in this script to fill a listbox has been validated by JSONLint. The code snippet below demonstrates how the parsed data is placed in arrays: pdata = jQuery.parseJSON(data); ctype = pdata[0]; stype = pdata[1]; ...

Steps for eliminating an element using jQuery from a variable filled with HTML code

I'm developing a forum where users have the ability to quote other users' comments. When a user clicks on "quote" for a comment, it captures the HTML of that comment and displays it in a box that says Quote: Original post by a member, similar t ...

`How can Simple Ajax Beginform be utilized in Asp.net MVC 4?`

Hello everyone, I'm a beginner in Asp.net MVC and I've been looking into using Ajax.BeginForm. However, when I tried implementing the code, it didn't work as expected. Could someone provide a very straightforward example of using Ajax.BeginF ...

Ways to center vertically aligned buttons within cards in a React application with Material-UI

I've encountered an issue with my ReactJS project using material-ui. I created 3 cards, each with a paragraph of varying lengths. This caused the buttons to be misaligned vertically in each card, as the position differs due to paragraph size differenc ...

Incrementally including DIV elements...one by one...2, 4, 6, 8, 10, 12

I am in the process of creating animated div boxes step by step that are activated when a button is pressed. The current code I have is working smoothly, with the box moving right and then left back to its original position. You can see a demo of this here ...

What could be the reason for not receiving a response from my API when using django rest framework with jquery?

Currently, I am utilizing Django REST framework to establish an API that functions seamlessly with cURL. Below is an example of a successful cURL request: curl -H 'Accept: application/json; indent=4' -u ratan:qazwsxedc123 http://127.0.0.1:8000/a ...

The utilization of 'ref' with React Styled Components is proving to be ineffective

Using refs in Styled Components has been tricky for me. When I attempt to access them in my class methods as shown below, I encounter the error message: Edit.js:42 Uncaught TypeError: this.....contains is not a function constructor(props) { .... ...

Mocking a function from within the method under test

I need to run tests on a method in my code that runs a series of functions, one of which sends an email. Is there a way to prevent this function from sending emails during testing? I want to avoid using conditional statements like the one below in my cod ...

Using Unity and C# to convert a JSON file into a structured data format

In my Unity C# project, I am developing a custom revision quiz program where users can import questions using JSON files with a specific structure: { "question": [ { "title": "What wave characteristic is measured on the vertical axis?", ...

Error with the jQuery scrolling plugin

Currently, the script is set up this way: jQuery(document).ready(function(){ var windheight = jQuery(window).height(); var windTop = jQuery(window).scrollTop(); var windbottom = windheight + windTop ; jQuery.fn.revealOnScroll = function(){ return this.e ...

Exploring data visualization within a JSX Component

I am attempting to dynamically render a Card component that is mapped from an array of objects. However, I am encountering an "unexpected token error" and the URL is not rendering as expected. The goal is to display five cards based on the data within the ...

Revamp the Vue component for better DRYness

Seeking advice on a more efficient way to improve the code below and make it DRY: <h2>{{ title }}</h2> <p>{{ subtitle }}</p> I am currently checking this.name for both the title and subtitle, wondering if there is a better implemen ...