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