Login


Using Ajax.BeginForm() with ASP.NET MVC

By Jonathan Wood on 4/21/2012
Language: C#JavaScript
Technology: AJAXASP.NETjQueryMVC
Platform: Windows
License: CPOL
Views: 168,948
Web Development » Client Scripting » AJAX » Using Ajax.BeginForm() with ASP.NET MVC

Screenshot of Demo

Download Source Code Download Source Code

Introduction

If you've been working with ASP.NET MVC, then you are almost certainly familiar with Html.BeginForm(). Html.BeginForm() is an HTML helper that makes it easier to write an HTML form block in an MVC view.

Listing 1 shows how you would use this helper in a Razor view. The using statement is used to ensure that the form is closed at the end of the using block. (This is exactly the same using keyword that we can use in C# code to ensure objects are disposed once execution leaves the using block.) The resulting HTML is shown in Listing 2.

Listing 1: Using Html.BeginForm() to create an HTML form

@using (Html.BeginForm())
{
    <fieldset>
        @Html.LabelFor(m => m.EmailAddress)
        @Html.TextBoxFor(m => m.EmailAddress)
        @Html.ValidationMessageFor(m => m.EmailAddress)
        <input type="submit" value="Submit" />
    </fieldset>
}

Listing 2: The HTML produced from Listing 1

<form action="/" method="post">
    <fieldset>
        <label for="EmailAddress">Email address</label>
        <input data-val="true" data-val-required="The Email address field is required."
            id="EmailAddress" name="EmailAddress" type="text" value="" />
        <span class="field-validation-valid" data-valmsg-for="EmailAddress"
            data-valmsg-replace="true"></span>
        <input type="submit" value="Submit" />
    </fieldset>
</form>

Note that, in the example above, the form is just posting back to the same action. Html.BeginForm() has a number of overloads that take additional arguments for doing things like posting to another action.

BeginForm() and AJAX

There are times when, in response to the user submitting a form, you don't want the entire page to refresh. For example, let's say you have a small form to send an email. When the user sends that email, you might want them to remain on the current page. Perhaps you'd like to simply pop up a message that says the email was sent, rather than refreshing the entire page or redirecting to another page. Depending on your application's workflow, this approach might provider a better user experience. And AJAX is the perfect solution for implementing this type of behavior.

You can use AJAX in combination with the HTML.BeginForm() helper. For example, you could write jQuery to handle $('form').submit() and simply write your own code to perform an AJAX post or any other custom tasks.

There's nothing about Html.BeginForm() that is incompatible with AJAX posts. However, if you are looking for syntax to perform an AJAX post that is as simple and easy as the syntax described above for performing regular posts, then you'll be interested in the Ajax.BeginForm() HTML helper.

Ajax.BeginForm()

Ajax.BeginForm() is designed to work very much like Html.BeginForm() except that Ajax.BeginForm(), as you might expect, performs an AJAX post.

Like Html.BeginForm(), Ajax.BeginForm() has a number of overloads that accept additional arguments. For example, you can specify the action and controller (just as you can with Html.BeginForm()). You can specify an element in your view that will automatically be updated with text that is returned from the action. You can also specify JavaScript functions that should be called in response to various events of the AJAX post.

Listing 3 shows some code that uses Ajax.BeginForm(). The code specifies an action in the current controller that the data will be posted to. It also specifies a JavaScript function to call after the AJAX post succeeds, and another function to call should the AJAX post fail.

My OnSuccess() function simply displays the string returned from the action. We could also return complex JSON objects if we needed additional information. My OnFailure() function just displays a general error message.

I should point out that, if there is an error in my action, it's up to me to handle that error and return an appropriate result. The OnSuccess() function will still be called. OnFailure() only gets called if there was an error during the process of calling or returning from the action.

Listing 3: Example using Ajax.BeginForm()

@using (Ajax.BeginForm("PerformAction",
    new AjaxOptions { OnSuccess = "OnSuccess", OnFailure = "OnFailure" }))
{
    <fieldset>
        @Html.LabelFor(m => m.EmailAddress)
        @Html.TextBoxFor(m => m.EmailAddress)
        @Html.ValidationMessageFor(m => m.EmailAddress)
        <input type="submit" value="Submit" />
    </fieldset>
}

<script type="text/javascript">

    function OnSuccess(response) {
        alert(response);
    }

    function OnFailure(response) {
        alert("Whoops! That didn't go so well did it?");
    }

</script>

The code above also demonstrates that client-side validation still works for forms created with Ajax.BeginForm(). Just make sure you include the appropriate JavaScript files.

A link to download my demo application is at the top of this article. It extends the code above into a small but fully functional project that illustrates this technique.

Conclusion

So, there you have my description of Ajax.BeginForm(), a convenience when implementing AJAX posts in your MVC views.

I should point out, however, that there are some who prefer not to use this helper. Some developers prefer using Html.BeginForm() and then writing jQuery to implement the AJAX post, a technique I described earlier in this article. These developers sometimes feel that writing their own jQuery gives them more control.

So it's probably a trade off between a convenience that requires less typing and an approach that gives you maximum control. As long as you understand the two approaches, you'll be in a good position to judge which one makes the most sense for you.

End-User License

Use of this article and any related source code or other files is governed by the terms and conditions of The Code Project Open License.

Author Information

Jonathan Wood

I'm a software/website developer working out of the greater Salt Lake City area in Utah. I've developed many websites including Black Belt Coder, Insider Articles, and others.