Simplest, easier and nice method to submit MVC form using jQuery AJAX:
$("formMapMarker").submit(function(e) {
if ($("formMapMarker").valid()) {
$.post($(this).attr("action"), $(this).serialize());
}
e.preventDefault();
});
Controller:
[HttpPost, ValidateInput(false)]
public ActionResult Create([Bind(Exclude="Id")] MapMarker marker)
{
if (ModelState.IsValid)
{
try
{
db.AddToMapMarkers(marker);
db.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
} else
return View();
}
$("formMapMarker").submit – assign function on form submit behaviour. $("formMapMarker").valid() – check if form passed validation (jQuery validation plugin used, see previous article). $.post($(this).attr("action"), $(this).serialize()) – get action path, collect form data and serialise it and make AJAX POST call to server. e.preventDefault() – cancel default behaviour with submit form button.
Just few lines of code and it works like a charm. :) BTW form submits will work with disabled JavaScript.
Reply