I have a simple razor view with a button that is supposed to add a new record to a table in my SQL DB. The button has attached an ajax function that calls the controller.
I tried two different controllers; both controllers work but add 2 new records instead of one. See below code snippets:
Button click event in razor view
$('#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 have been working on this for almost 2 days, debugged through the entire code but can't find the cause or a clue where to dig deeper. When I execute the SQL stored procedure manually inside SSMS it does add only one record. Any help will be appreciated!
Additional info: No submits, no other buttons on the view