Making an Ajax Form with jQuery in ASP.NET MVC
Posted in jQuery, ASP.NET by JarrettV on 2/20/2010 2:07:38 PM - CSTThe latest release of jQuery 1.4 makes it even easier to create an Ajax form in ASP.NET MVC. The process involves creating two partial views, one for the form and one for successful post of the form. Then, we'll create an action method for handling form posts. Finally, we'll wire up the jQuery events to make it post within the page.
Create the Form Partial View
First, create a view model to hold the form values.
public class ContactViewModel
{
public string Name { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public string Message { get; set; }
}
Next, create a basic HTML form with validation messages as shown below (call it ContactForm.ascx).
<%@ Control Language="C#" AutoEventWireup="true" Inherits="ViewUserControl<ContactViewModel>" %>
<div id="contact">
<h4>Send A Message</h4>
<form method="post" action="<%= Url.Action("SendMessage", "Contact") %>">
<fieldset>
<label for="name">Name <small>(required)</small></label><%= Html.ValidationMessage("name") %>
<%= Html.TextBox("name", Model.Name) %>
<label for="email">Email <small>(required)</small></label><%= Html.ValidationMessage("email") %>
<%= Html.TextBox("email", Model.Email) %>
<label for="phone">Phone</label><%= Html.ValidationMessage("phone") %>
<%= Html.TextBox("phone", Model.Phone) %>
<label for="message">Message <small>(required)</small></label><%= Html.ValidationMessage("message")%>
<%= Html.TextArea("message", Model.Message, 4, 100, null) %>
<%= Html.ValidationMessage("error") %>
<input type="submit" value="Send Message" />
</fieldset>
</form>
</div>
Now include this form into any view with Html.RenderPartial("ContactForm", new ContactModel());
Also create a success partial view (call it ContactSuccess.ascx):
<%@ Control Language="C#" AutoEventWireup="true" Inherits="ViewUserControl<ContactViewModel>" %>
<div id="contact">
<h4>Thank You!</h4>
<p class="response"><strong>Your message was sent successfully.</strong> We will get back to you as soon as possible.</p>
<p>
Name: <%= Model.Name %><br />
Email: <%= Model.Email %><br />
Phone: <%= Model.Phone %><br />
Message: <%= Model.Message %>
</p>
</div>
This view will replace the form upon successful form submission.
Handle SendMessage Action
Create a new ContactController class and add the following action method:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult SendMessage(ContactViewModel model)
{
ValidateContactModel(model);
if (this.ModelState.IsValid)
{
try
{
// get contact configuration
SendContactMessage(model);
return PartialView("ContactSuccess", model);
}
catch (Exception ex)
{
//TODO: log/notify error
ModelState.AddModelError("error", "An unexpected error occured, please contact the webmaster.");
}
}
return PartialView("ContactForm", model);
}
This code will validate the contents of the form post and then send the message. If there are any errors, it will redisplay the form. Otherwise, it'll display the contact success partial view.
Note: model validation and sending email is outside the scope of this article, see here for the code.
Wire jQuery Event for AJAX Form
Finally, let's add the jQuery code to bottom of the page. If you'd like, you can put this in a javascript file and link to it.
$(document).ready(function () {
$('#contact form').live('submit', function () {
$.post($(this).attr('action'), $(this).serialize(), function (data) {
$("#contact").replaceWith($(data));
});
return false;
});
});
This code uses the updated live event support on form submits to easily wire up the submit button. The submit button does an AJAX post to the action. The action will return either the same form (with errors) or the success partial view. It replaces the current form with the response data. Since we are using the live event support, we do not have to worry about re-wiring the submit event each time the error form is returned.
You can see the entire source code in the AtomSite source code.
Comments
Posted by Josh on 3/27/2010 9:58:04 PM - CST
Posted by Josh on 3/27/2010 10:15:16 PM - CST