Ajaxify your MVC form in 30 seconds

I was playing around with the ASP.NET MVC 2 Framework and needed to submit my form using Ajax instead of a full form post. I noticed the MicrosoftAjax.js and MicrosoftMvcAjax.js file that came with the project so I had high hopes for something good being included in the framework that would simplify that task. And indeed. By simply using the AjaxHelper instead of the HtmlHelper you can have your form submitted via Ajax. MVC does all the hard work for you.

Simply  replace

<% using (Html.BeginForm()) { %>

with

<% using (Ajax.BeginForm(new AjaxOptions() { OnComplete = "OnFormSubmitComlete" })) {%>

and you’re done. No changes to your Controller are required. There are some nice AjaxOptions you can specify and BeginForm has a bunch of overloads as well. In this case I’ve specified a javascript method name “OnFormSubmitComlete” to be called after the form has been submitted and the response received.

<script type="text/javascript">
function OnFormSubmitComlete(content)
{
alert("Saved with Ajax. Awesome!");
}
</script>

Make sure you’re including the MicrosoftAjax.js and MicrosoftMvcAjax.js scripts that come with your project.

This entry was posted in .NET and tagged , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*