Sending HTML Form Data in ASP.NET Web API: Form-urlencoded Data
by Mike Wasson
Part 1: Form-urlencoded Data
This article shows how to post form-urlencoded data to a Web API controller.
[!NOTE] Download the completed project.
HTML forms use either GET or POST to send data to the server. The method attribute of the form element gives the HTTP method:
[!code-htmlMain]
1: <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.
Typically, you will send a complex type, composed of values taken from several form controls. Consider the following model that represents a status update:
[!code-csharpMain]
1: namespace FormEncode.Models
2: {
3: using System;
4: using System.ComponentModel.DataAnnotations;
5:
6: public class Update
7: {
8: [Required]
9: [MaxLength(140)]
10: public string Status { get; set; }
11:
12: public DateTime Date { get; set; }
13: }
14: }
Here is a Web API controller that accepts an Update
object via POST.
[!code-csharpMain]
1: namespace FormEncode.Controllers
2: {
3: using FormEncode.Models;
4: using System;
5: using System.Collections.Generic;
6: using System.Net;
7: using System.Net.Http;
8: using System.Web;
9: using System.Web.Http;
10:
11: public class UpdatesController : ApiController
12: {
13: static readonly Dictionary<Guid, Update> updates = new Dictionary<Guid, Update>();
14:
15: [HttpPost]
16: [ActionName("Complex")]
17: public HttpResponseMessage PostComplex(Update update)
18: {
19: if (ModelState.IsValid && update != null)
20: {
21: // Convert any HTML markup in the status text.
22: update.Status = HttpUtility.HtmlEncode(update.Status);
23:
24: // Assign a new ID.
25: var id = Guid.NewGuid();
26: updates[id] = update;
27:
28: // Create a 201 response.
29: var response = new HttpResponseMessage(HttpStatusCode.Created)
30: {
31: Content = new StringContent(update.Status)
32: };
33: response.Headers.Location =
34: new Uri(Url.Link("DefaultApi", new { action = "status", id = id }));
35: return response;
36: }
37: else
38: {
39: return Request.CreateResponse(HttpStatusCode.BadRequest);
40: }
41: }
42:
43: [HttpGet]
44: public Update Status(Guid id)
45: {
46: Update update;
47: if (updates.TryGetValue(id, out update))
48: {
49: return update;
50: }
51: else
52: {
53: throw new HttpResponseException(HttpStatusCode.NotFound);
54: }
55: }
56:
57: }
58: }
[!NOTE] This controller uses action-based routing, so the route template is ???api/{controller}/{action}/{id}???. The client will post the data to ???/api/updates/complex???.
Now let???s write an HTML form for users to submit a status update.
[!code-htmlMain]
1: <h1>Complex Type</h1>
2: <form id="form1" method="post" action="api/updates/complex"
3: enctype="application/x-www-form-urlencoded">
4: <div>
5: <label for="status">Status</label>
6: </div>
7: <div>
8: <input name="status" type="text" />
9: </div>
10: <div>
11: <label for="date">Date</label>
12: </div>
13: <div>
14: <input name="date" type="text" />
15: </div>
16: <div>
17: <input type="submit" value="Submit" />
18: </div>
19: </form>
Notice that the action attribute on the form is the URI of our controller action. Here is the form with some values entered in:
When the user clicks Submit, the browser sends an HTTP request similar to the following:
[!code-consoleMain]
1: POST http://localhost:38899/api/updates/complex HTTP/1.1
2: Accept: text/html, application/xhtml+xml, */*
3: User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)
4: Content-Type: application/x-www-form-urlencoded
5: Content-Length: 47
6:
7: status=Shopping+at+the+mall.&date=6%2F15%2F2012
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.
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 following code shows how to post form data using jQuery.
[!code-htmlMain]
1: <script type="text/javascript">
2: $("#form1").submit(function () {
3: var jqxhr = $.post('api/updates/complex', $('#form1').serialize())
4: .success(function () {
5: var loc = jqxhr.getResponseHeader('Location');
6: var a = $('<a/>', { href: loc, text: loc });
7: $('#message').html(a);
8: })
9: .error(function () {
10: $('#message').html("Error posting the update.");
11: });
12: return false;
13: });
14: </script>
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.
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.
[!code-csharpMain]
1: [HttpPost]
2: [ActionName("Simple")]
3: public HttpResponseMessage PostSimple([FromBody] string value)
4: {
5: if (value != null)
6: {
7: Update update = new Update()
8: {
9: Status = HttpUtility.HtmlEncode(value),
10: Date = DateTime.UtcNow
11: };
12:
13: var id = Guid.NewGuid();
14: updates[id] = update;
15:
16: var response = new HttpResponseMessage(HttpStatusCode.Created)
17: {
18: Content = new StringContent(update.Status)
19: };
20: response.Headers.Location =
21: new Uri(Url.Link("DefaultApi", new { action = "status", id = id }));
22: return response;
23: }
24: else
25: {
26: return Request.CreateResponse(HttpStatusCode.BadRequest);
27: }
By default, Web API tries to get simple types from the request URI. The FromBody attribute tells Web API to read the value from the request body.
[!NOTE] Web API reads the response body at most once, so only one parameter of an action can come from the request body. If you need to get multiple values from the request body, define a complex type.
Second, the client needs to send the value with the following format:
[!code-xmlMain]
1: =value
Specifically, the name portion of the name/value pair must be empty for a simple type. Not all browsers support this for HTML forms, but you create this format in script as follows:
[!code-javascriptMain]
1: $.post('api/updates/simple', { "": $('#status1').val() });
Here is an example form:
[!code-htmlMain]
1: <h1>Simple Type</h1>
2: <form id="form2">
3: <div>
4: <label for="status">Status</label>
5: </div>
6: <div>
7: <input id="status1" type="text" />
8: </div>
9: <div>
10: <input type="submit" value="Submit" />
11: </div>
12: </form>
And here is the script to submit the form value. The only difference from the previous script is the argument passed into the post function.
[!code-javascriptMain]
1: $('#form2').submit(function () {
2: var jqxhr = $.post('api/updates/simple', { "": $('#status1').val() })
3: .success(function () {
4: var loc = jqxhr.getResponseHeader('Location');
5: var a = $('<a/>', { href: loc, text: loc });
6: $('#message').html(a);
7: })
8: .error(function () {
9: $('#message').html("Error posting the update.");
10: });
11: return false;
12: });
You can use the same approach to send an array of simple types:
[!code-javascriptMain]
1: $.post('api/updates/postlist', { "": ["update one", "update two", "update three"] });
Additional Resources
Part 2: File Upload and Multipart MIME
|