MVC AJAX Form with jQuery Form Plugin and jQuery Thickbox
In a previous post, I showed how to submit an AJAX form in MVC with the jQuery Thickbox and the built-in MVC AJAX helpers. If you read that post first, it will show the complete context for how to simply submit an AJAX form that is being rendered inside a jQuery Thickbox with built-in MVC AJAX helpers. But what if you want to stick to a pure jQuery solution? That is also simple enough to do. Instead of using the Ajax.BeginForm() method, you can use the jQuery Form Plugin. The code is almost identical to the previous implementation. The only differences are in the Index.ascx partial view:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MvcAjaxForm.Models.ContactMessage>" %> <script type="text/javascript"> $(function() { $("#contactForm").ajaxForm({ target: '#contactArea' }); }); </script> <h2>Contact</h2> <form id="contactForm" action="<%=Url.Action("Index", "Contact") %>" method="post"> <div id="contactArea"> Email Address: <%=Html.TextBox("EmailAddress") %> <br /><br /> Message: <%=Html.TextArea("MessageText")%> <input type="submit" /> </div> </form>
On line 11, you will now specify a normal HTML form just like you might specify any other form in MVC (you could also use the Html.BeginForm() method as well if you have that preference). The only additional thing you have to implement is the one line of code shown on line 5 above. This is making a call to the ajaxForm() method (that comes in the Form Plugin library) and passes in the options to indicate that the response from the server should be displayed in the "contactArea" div. This is just one example of how to use the Form plugin – you can also find numerous example within the Form Plugin's documentation site.