What is causing my controller action to create two new records instead of just one?

My current issue involves a simple Razor view featuring a button designed to add a new record to a table within my SQL database. The button is equipped with an Ajax function that triggers a call to the controller.

I've experimented with two different controllers, both of which technically work but result in the addition of 2 new records instead of just one. Below are snippets of the relevant code:

Razor view button click event

$('#addLike')
    .click(function (e) {
        var proposalId = 12;
        var url = "@Url.Action("AddLike", "Proposal")/?proposalId=" + proposalId;
            $.ajax({
                type: "POST",
                url: url,
                dataType: "json",
                traditional: true,
                success: function(response) {
                    window.location.href = actions.common.proposals;
                }
            });
    });

Class model

public class Proposal_Likes
{
    public int? Proposal_Id { get; set; }
    public int Id  { get; set; } (... Identity, DatabaseGenerated)
}

Controller

public ActionResult AddLike(int proposalId)
{
    var proposal_Like =  new Proposal_Likes
    {
        Proposal_Id = proposalId
    };

    UnitOfWork.InsertOrUpdate(proposal_Like);
    UnitOfWork.Commit();

    return Json("Success");
}

Alternative Controller

public ActionResult AddLike(int proposalId)
{
        using (SqlConnection con = new SqlConnection(cs))
        {
            using (SqlCommand cmd = new SqlCommand("addProposalLike", con))
            {
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add("@propsalId", SqlDbType.Int).Value = proposalId;
                con.Open();
                cmd.ExecuteNonQuery();
            }
        }

    return Json("Success");
}

I've spent nearly 48 hours troubleshooting this issue, meticulously tracing through the code without pinpointing the root cause or where to further investigate. Interestingly, when I manually execute the SQL stored procedure in SSMS, it successfully adds only one record. Any assistance or insights would be greatly appreciated!

Additional information: No form submissions present and no other buttons on the view

Answer №1

After some investigation, I was able to identify the root cause of the issue: In my ajax function, I had been using a parameter in the url.Action method to pass it to an ActionResult controller:

$.ajax({
type: "POST"
var url = "@Url.Action("AddLike", "Proposal")/?proposalId=" + proposalId;
...

public ActionResult AddLike(int proposalId)
{ ...}

This lead to the controller being called twice, for reasons unknown to me. When I chose to instead pass the parameter through the data section of the ajax call like this:

    var url = "@Url.Action("AddLike", "Proposal")";
         $.ajax({
             type: "POST",
             url: url,
             dataType: "json",
             data: {
                 proposalId: 24,
                    },

by incorporating it into a model used by both the view and the controller:

public class ProposalViewModel
{
    public int proposalId { get; set; }
}

public ActionResult AddLike(ProposalViewModel model)
{   
    var propId = model.proposalId
    ...
}

The controller is now only called once as expected.

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 the best way to assess each item in an array and apply the useState() hook based on a specific condition

I am currently working on a simulation for a blackjack hand and have run into an issue with my code. The game follows these steps: users receive two random cards and a total point value, then click 'hit' to draw another random card from the deck. ...

Preventing bots and spiders from infiltrating the ad network. Stepping up efforts to block unwanted traffic

We are facing a constant battle against bots and spiders with our in-house ad system, striving for 100% valid impressions. To achieve this goal, I conduct experiments on a specific ad zone that is only displayed on one page of our site. By comparing the G ...

I am seeking assistance to utilize Flexbox to completely fill the height of my computer screen

Seeking assistance in utilizing Flexbox to occupy 100% of my computer screen's height, all while ensuring responsiveness: View of my current sign-in page on Chrome (Note the whitespace): https://i.sstatic.net/pJFOi.png Examining my existing fronten ...

Troubleshooting issues with the add-comment and remove-comment functionalities in a react-redux application

I'm working on a comment widget using react-redux. I've encountered an issue where, when I click on the add comment button, nothing happens. Also, when I try to delete a comment, I get an error saying that map is not a function even though I am p ...

Sending complex data types like IEnumerable models to a controller in ASP.NET MVC

I need to make changes to a view where a set of images related to a specific album can be edited by updating their descriptions and setting them as the cover photo. EditImageViewModel.cs public class EditImageViewModel { public int ImageId{get;set;} ...

Having trouble customizing a particular view within Angular

I am struggling to customize the background of a specific view in Angular. When I tried to style it with the code below, the entire view disappeared. Here is the relevant code: HTML (index.html): <div class="col-md-8 col-md-offset-2"> <div ng ...

Sweet alert is taking precedence over the standard alert function when used in a loop

When I call the sweet alert function inside a loop, it only shows up once. It seems like it's overriding the previous sweet alert because when I use a simple alert, it pops up twice. What I want is for the sweet alert to show the second or third alert ...

A problem arises when making an ajax call

I'm struggling with an Ajax call made using the jQuery .blur() method. Every time I try to execute it, an error message pops up. Any idea why this is happening? Here's my jQuery/Ajax Code: <script> $("#given_name").blur(function(){ va ...

Assigning a variable in jQuery to a PHP variable that has not been defined can halt the script

Here is the code snippet for a document ready function: $(document).ready(function(){ var id = <?php echo "" ?>; alert('boo'); if(id!=0){ $(' ...

Is it necessary for Webpack to process the index.html file for Vue applications?

I am facing an issue with my index.html file where the assets inside the head tag are not loading as images but as the index.html file itself. I have included the following links in my head tag: <link rel="apple-touch-icon" sizes="60x60" href="./assets ...

Jquery failing to trigger click() on a div with an id

Within my erb file, there exists a script that looks like the following: function checkJquery() { if(window.jQuery) { jQuery(document).ready(function() { alert('onready'); $('div#habla_topbar_div').click(function( ...

To retrieve the first td element by clicking a button within the corresponding row using JQuery

This may seem like a straightforward inquiry, but despite my best efforts, I have been unable to find a solution. I am looking to create a function that will allow me to click a button located in the 3rd td element and display the text from the first td e ...

The knockout.js subscribe function isn't activating during the initial set

In my model class, I have defined observables and I am looking to subscribe to their sets. Below is the code snippet that showcases what I currently have: var dto = function (data) { var self = this; self.Value1 = ko.observable(data.Value1); s ...

Create dynamic combo boxes using jQuery

My goal is to display a text field on the page if a user has only one credit card number in the database. However, if the user has multiple credit card numbers stored, I want to display all of them in a combo box. Below is the ajax response that I am rece ...

Unable to download essential dependencies using NPM

After cloning a repository for a MEAN stack application, the first step was to run npm install. The installation process resulted in: added 1580 packages from 1887 contributors and audited 15249 packages in 281.586s found 18 vulnerabilities (5 low, 12 mod ...

When using Bcrypt compare(), the result is consistently incorrect

After implementing this code for comparison, I encountered an issue with the compare password functionality. UserSchema.pre('save', async function() { const salt = await bcrypt.genSalt(10) this.password = await bcrypt.hash(this.password, ...

I can't understand why my server is displaying an error on the browser stating "This site can't be reached ERR_UNSAFE_PORT" while it is functioning flawlessly on the terminal

I have created an index.html file, along with index.js and server.js. In the server.js file, I have included the following code: const express = require("express"); const path = require("path" ); const app = express(); app.use(" ...

Leveraging Parameters in Ajax with jQuery and JavaScript

I've been exploring jQuery and trying to update a specific TD element with innerHTML. However, I'm stuck on how to capture the value of a parameter. In this scenario, my goal is to grab the user-id "1234" in order to update the TD identified as ...

How should the nonce be properly set in the csp policy?

I've been attempting to incorporate a nonce into the csp policy but it's not functioning as anticipated. Here's the code snippet I'm currently using for testing purposes: server.js express.use(function(req, res, next) { res.set( ...

What could be the reason for JavaScript delaying the execution of DOM statements until a variable is true?

Today I've been tackling numerous bugs, but there's one particularly tricky bug that has me stumped. The snippet of code below pertains to a basic logon page. Currently, the only valid username is 'admin' and the corresponding password ...