Ajax.BeginForm: Clear Form After Submit

If you are using ASP.NET MVC, here is a simple tip on how to clear an ajax form after successfully submitting it with a little help from jQuery.

The first step is to get the jQuery Form Plugin, add it to your Scripts folder and then add a script reference to it in your masterpage. jQuery is already included in the projects since the release of the MVC so you don’t need to download and include it.

<script src="../../Scripts/jquery-1.2.6.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.form.js" type="text/javascript"></script>

You can then create a function that will call the clearForm function from the Form Plugin.

<script type="text/javascript">
   function done() {
       $('form').clearForm();
   }
</script>

Now you can use the OnSuccess callback from the Ajax.BeginForm helper to point to the done() function we just created. This function will be called automatically after the form submit completed successfully.

<% using (Ajax.BeginForm("SaveComment", new AjaxOptions { 
         UpdateTargetId = "feedback", 
         InsertionMode = InsertionMode.Replace, 
         OnSuccess = "done"}))
{ %>

Here is the complete code:

<script type="text/javascript">
            function done() {
                $('form').clearForm();
            }
    </script>
    <h2 id="feedback"></h2>
    <fieldset>
        <% using (Ajax.BeginForm("SaveComment", new AjaxOptions { 
               UpdateTargetId = "feedback", 
               InsertionMode = InsertionMode.Replace, 
               OnSuccess = "done"}))
           { %>
            <dl>
                <dd><%= Html.TextBox("Comment.Author")%></dd>
                <dd><input type="submit" title="Submit" /></dd>
            </dl>
        <% } %>
    </fieldset>

 

blog comments powered by Disqus