Here is a bizarre problem.
I call an ActionResult in my controller from jQuery on a view.
Here is the jQuery
$(document).ready(function () {
$('.addNoteLink').button();
$('.addNoteLink').click(function () {
var cid = $('#CaseID').val();
var notetext = $('#NoteText').val();
var url = "/Cases/AddNoteText";
$.ajax({
type: "POST",
url: url,
data: { id: cid, note: $('#NoteText').val() }
});
});
});
Here is the controller method:
public ActionResult AddNoteText(int id, string note)
{
try
{
if (ModelState.IsValid)
{
CaseNotes notes = new CaseNotes
{
CasesID = id,
NoteDate = DateTime.Now,
NoteText = note
};
db.CaseNotes.Add(notes);
db.SaveChanges();
}
}
catch
{
}
return RedirectToAction("Edit", id);
}
Here is the html related to the jQuery:
<div class="editor-label">
@Html.Label("Enter notes here and click Add Note Text")
</div>
<div class="textarea-field">
<input id = "NoteText" type="text" />
</div>
@Html.ActionLink("Add Note Text", "AddNoteText", new { id = Model.CasesID }, new { @class = "addNoteLink" })
When the jQuery calls this method, if I follow with a breakpoint, the parameters are pass correctly, the ModelState is valid, it goes into the notes entity and assigns values etc. When the breakpoint hits db.CasesNotes.Add(notes) the breakpoint returns to the top of the function and goes down again until it hit the notes entity then jumps to db.SaveChanges()
then returns to the top AGAIN, goes thru the method and errors out because the parameters have been cleared by that point. The original record gets inserted though.
Any thoughts?
If you subscribe on an anchor with jQuery click the browser will still execute the default action (e.g follow the link) when you click on the link. That’s why your action called twice.
You need call to call the preventDefault() on the event object to cancel the browser default behavior: