jvance.com

.net, c#, asp.net, linq, htpc, woodworking

Making an Ajax Form with jQuery in ASP.NET MVC

Posted in ASP.NET, MVC, jQuery by JarrettV on 2/20/2010 2:07:00 PM - CST

The 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.

Example Form

You can see the entire source code in the AtomSite source code.

Comments

Gravatar
Posted by Josh on 3/27/2010 9:58:04 PM - CST
I've played with this for an hour and I can't get it to work. I don't see where a form with an id of 'contact form' is created. I keep getting javascript errors.
Gravatar
Posted by Josh on 3/27/2010 10:15:16 PM - CST
Never mind, dumb mistake on my part. Thanks for the tutorial. Very helpful.
Trackback from Thomas goes .NET on 7/28/2010 4:34:34 AM - CST

ASP.NET MVC - Formulare per Ajax verarbeiten

Disclaimer: Ich bin kein Ajax-Entwickler. Als das Thema vor 5 Jahren auf den Tisch kam, hatte ich schon einige Jahre mit XmlHttpRequest im Internet Explorer gearbeitet, aber mich eigentlich schwerpunktmäßig immer auf die Serverseite konzentriert. Das ...
Gravatar
Posted by Oli on 2/20/2011 12:11:00 PM - CST
you probably dont want to bother with autoeventwireup..
cheers, o
Gravatar
Posted by www.google.com/accounts/o8/id on 2/23/2011 2:45:47 AM - CST
It was useful! Thanks!
Gravatar
Posted by www.google.com/accounts/o8/id on 3/13/2011 5:52:33 AM - CST
great, Thanks

Add Comment

Login using
Google Yahoo flickr AOL
and more
Or provide your details
Please enter your name. Please enter a valid email. Please enter a valid website.
Please supply a comment.
4.0 (7)
on 2/25/2011 11:40:41 AM - CST

Recent Entries

Valid XHTML 1.0 Strict
© Copyright 2011 Powered by AtomSite 1.4.0.0