Skip to content

Instantly share code, notes, and snippets.

@RimonEkjon
Forked from jlarsson/ajaxform.js
Last active August 29, 2015 14:05
Show Gist options
  • Save RimonEkjon/b90af39af9be1e54b21c to your computer and use it in GitHub Desktop.
Save RimonEkjon/b90af39af9be1e54b21c to your computer and use it in GitHub Desktop.
JQuery- MVC ajaxForm.js
/*
Canonical ASP.NET MVC usage
// site.css
.ajax-progress-show, .ajax-progress-error { display: none; }
// index.cshtml
@Html.Partial("partial",new SampleModel())
// partial.cshtml
<form class="ajax-form" role="form" data-ajax-action="@Url.Action("AjaxSave","SampleController")">
@Html.AntiForgeryToken()
@Html.TextBoxFor(m => m.SomeProperty)
<button class="ajax-submit ajax-progress-hide">Default Save</button>
<button class="ajax-submit ajax-progress-hide" data-ajax-action="@Url.Action("AjaxAlternateSave","SampleController")">Alternate save</button>
<div class="ajax-progress-show">Saving..</div>
<div class="ajax-progress-error">An error occured..</div>
</form>
// backend
class SampleController: Controller{
[HttpPost]
[ValidateAntiForgeryToken]
public PartialViewResult AjaxSave(SampleModel model){
ModelState.Clear();
// do stuff
return PartialView("partial");
}
[HttpPost]
[ValidateAntiForgeryToken]
public PartialViewResult AjaxAlternateSave(SampleModel model){
ModelState.Clear();
// do stuff
return PartialView("partial");
}
}
*/
if (!jQuery) {
throw new Error("ajaxform requires jQuery");
}
(function ($) {
var ajaxSubmit = function () {
// button or whatever that triggered a click (which we interpret as ajax submit)
var $this = $(this);
// get enclosing, which typically is a partial
var $form = $this.closest('form.ajax-form');
// where to post?
var postUrl = $this.attr('data-ajax-action') || $form.attr('data-ajax-action');
// get form data
var data = $form.serialize();
// toogle elements
$('.ajax-progress-show', $form).show();
$('.ajax-progress-hide', $form).hide();
$('.ajax-progress-error', $form).hide();
// post data
$.ajax({
type: 'post',
url: postUrl,
data: data,
dataType: 'html',
cache: false
})
.done(function (markup) {
// we expect to get back a new fully filled in form
$form.replaceWith(markup);
})
.error(function () {
$('.ajax-progress-show', $form).hide();
$('.ajax-progress-hide', $form).show();
$('.ajax-progress-error', $form).show();
});
return false;
};
$(document).on('click', '.ajax-submit', ajaxSubmit);
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment