Angry Monkeys

Angry Monkeys is a web dev team based in Melbourne. We build software for smarter simians.

AJAX with JQuery and MVC

posted March 09th 2009

I love JQuery. I used to hate it. But now I love it. I especially love it when working with .NET MVC.

I’m building an app at the moment which allows a user to upload a file, and during the process they can choose to have a link to the file sent to them. It’s an optional thing, just to save them having to cut and paste a link. It’s a nothing feature… a bit of a freebie, and I didn’t want to spend a lot of time on it.

More importantly, I didn’t want to stop the user in their tracks to do this particular task. The email field just sits there in the Nav, and if you want to use it you can and if you don’t want to you don’t have to. Most importantly, however, if they user did choose to fill in the email box at some point, I didn’t want to take them away from what they were doing by doing a full post of the page. Enter AJAX!

Ajax is nothing new, and neither is MVC. But in the world of .NET they’re both still kinda fresh. So here is how I went about creating a neat little emailer in the middle of a page.

First of all, some HTML. The simpler the better!

<form id="EmailForm" action="/test/email" method="post">
    <input id="emailAddress" type="text" value="email address" />
    <input type="submit" value="go" />
</form>

Then some JQuery….

$("#EmailForm").submit(function() {                                    //capture the submit event of our form
    $.ajax({                                                           //create an AJAX request
        type: "POST",                                                  //use POST (we could also load this from the form if wanted to)
	url: $("#EmailForm").attr("action"),                           //get the URL from the form
	data: $("#EmailForm").serialize(),			       // this one line turns our whole form into tasty AJAX snacks!
	success: function() {
	    alert("win!!!1!1!")                                        //we got a 200 back...it worked!
	},
	error: function(XMLHttpRequest, textStatus, errorThrown) {
	    alert("epic fail!")                                         //something went HORRIBLY wrong!
	}
    });
    return false;                            //don't forget to cancel the event so we don't submit the page!
});

OK, so far so good. All pretty straight forward. That, of course, would work with any server side technology…not just .NET MVC. BUT, the reason I like this so much is because with MVC we don’t even have to bother with a responding page. Previously in .NET you’d have to create an ASPX page or web service just to handle this AJAX request (or a library of them perhaps). If you have a route setup already, all we need is a method in our controller class to handle the AJAX request!

[AcceptVerbs(HttpVerbs.Post)]
public void Email(FormCollection form)
{
    string emailAddress = form["emailAddress"];
    // validate the email address
    .....
    //create the email message
    MailMessage msgMail = new MailMessage("info@angrymonkeys.com.au", emailAddress);

    // do some email content stuff
    .......

    // send the email!
    smtp.Send(msgMail);
}

That’s all there is to it! Of course, this particular method doesn’t return anything to the AJAX callback (except an error if something breaks!)….. so you’d probably want to return something if the address is invalid and show a nice error to the user. But I’m keeping it simple here.

The crux of what is cool about this, however, is the separation between HTML and code. Because MVC doesn’t have tightly coupled Pages/Classes/Code behind, you can not only reduce the amount of code you write (by doing away with superfluous aspx pages and reusing existing functions), but you increase the number of ways you can use the code you have already written. Doing an AJAX request becomes nothing other than another type of View…. the Controller doesn’t have to care where the request is coming from and it means neither do you!

Comments

  1. August 27th, 2009 | 9:18 am

    [...] to Vote[Del.icio.us] AJAX with JQuery and MVC | Angry Monkeys (8/27/2009)Thursday, August 27, 2009 from [...]

  2. nachid
    September 9th, 2009 | 8:25 am

    I copied your code to a brand new asp.mvc projet but there is no way to make it working
    the FormCollection form is always empty
    Can you send me your Visual studio solution ( I can also send mine)
    Thanks

  3. September 10th, 2009 | 12:27 am

    Hi Nachid,

    You may want to just check that you’re serializing the form you want to send correctly. If you’re not using it already, I recommend installing Firebug for Firefox and checking the console for what data is getting sent to your controller.

    I can’t send you my VS solution unfortunately, but I’m happy to help in any other way I can!

    Cheers!

  4. nachid
    September 10th, 2009 | 9:22 am

    Thank you for your quick answer
    I don’t understand why but I solved the issue by adding a name attributre to the input element

  5. September 10th, 2009 | 3:24 pm

    Yes that would be right. All form elements need a “name” attribute to be submitted to the server in a form post. This will then be the name you use to access the value in the form collection on the server.

    Glad you worked it out!

    Cheers,
    Alan

Leave a reply