Part 1: Form-urlencoded Data

Overview of HTML Forms

HTML forms use either GET or POST to send data to the server. The method attribute of the form element gives the HTTP method:

<form action="api/values" method="post">

The default method is GET. If the form uses GET, the form data is encoded in the URI as a query string. If the form uses POST, the form data is placed in the request body. For POSTed data, the enctype attribute specifies the format of the request body:

enctype

Description

application/x-www-form-urlencoded

Form data is encoded as name/value pairs, similar to a URI query string. This is the default format for POST.

multipart/form-data

Form data is encoded as a multipart MIME message. Use this format if you are uploading a file to the server.

Part 1 of this article looks at x-www-form-urlencoded format. Part 2 describes multipart MIME.

Sending Complex Types

Typically, you will send a complex type, composed of values taken from several form controls. Consider the following model that represents a status update:

Notice that the request body contains the form data, formatted as name/value pairs. Web API automatically converts the name/value pairs into an instance of the Update class.

Sending Form Data via AJAX

When a user submits a form, the browser navigates away from the current page and renders the body of the response message. That's OK when the response is an HTML page. With a web API, however, the response body is usually either empty or contains structured data, such as JSON. In that case, it makes more sense to send the form data using an AJAX request, so that the page can process the response.

The jQuery submit function replaces the form action with a new function. This overrides the default behavior of the Submit button. The serialize function serializes the form data into name/value pairs. To send the form data to the server, call $.post().

When the request completes, the .success() or .error() handler displays an appropriate message to the user.

Sending Simple Types

In the previous sections, we sent a complex type, which Web API deserialized to an instance of a model class. You can also send simple types, such as a string.

Note

Before sending a simple type, consider wrapping the value in a complex type instead. This gives you the benefits of model validation on the server side, and makes it easier to extend your model if needed.

The basic steps to send a simple type are the same, but there are two subtle differences. First, in the controller, you must decorate the parameter name with the FromBody attribute.