I'm clearly missing something but can't for the life of me see what it is so would appreciate if anyone could point out my error.
I have a simple details page with a form to add comments to the selected detail.
I have a view with the following formed contained within it:
@using (Html.BeginForm("Details", "Home", FormMethod.Post, new { id ="commentForm" }))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<div class="form-group">
@Html.LabelFor(model => model.NewComment.Name);
@Html.TextBoxFor(model => model.NewComment.Name, new { @class = "form-control" })
</div>
<div class="form-group">
@Html.LabelFor(model => model.NewComment.Body);
@Html.TextAreaFor(model => model.NewComment.Body, new { @class = "form-control" })
</div>
<input type="submit" class="btn btn-primary" value="Add Comment" />
}
This view then calls the following c# controller method:
[HttpPost]
public ActionResult Details(int id,DetailsViewModel model)
{
if (!ModelState.IsValid)
return View(model);
var content =_data.First(c => c.Id == id);
content.Comments.Add(model.NewComment);
return View(new DetailsViewModel(content));
}
If I use the form without adding any additional code to catch the submit with jquery then this all works correctly.
When i add the following JQuery code to the page then the above server code is not executed (I know i am not actually returning any json in the above method but if the method is not executed that seems redundant for now?):
$(document).ready(function () {
$("#commentForm").submit(function (event) {
event.preventDefault();
var url = $(this).attr('action');
$.getJSON(url, $(this).serialize(), function (comment) {
alert(comment)
});
});
});
If is also worth noting that if i add any alerts around the getjson call then these all fire correctly.
Does anyone have any ideas about what i'm doing wrong?