[ASP. NET Web API tutorial] 5.2 send HTML form data: URL-encoded form data, api5.2
Note: This article is part of the [ASP. NET Web API series tutorial]. If this is the first time you read this series of tutorials, read the previous content first.
5.2 Sending HTML Form Data
5.2 send HTML form data
This article cited from: http://www.asp.net/web-api/overview/working-with-http/sending-html-form-data,-part-1
By Mike Wasson | jun e 15,201 2
Author: Mike Wasson | Date:
Part 1: Form-urlencoded Data
Part 1: URL-encoded form data
This article shows how to post form-urlencoded data to a Web API controller.
This article shows how to submit URL-encoded form data to the Web API controller.
- Overview of HTML Forms
HTML form Overview
- Sending Complex Types
Send compound type
- Sending Form Data via AJAX
Send form data through AJAX
- Sending Simple Types
Simple sending type
Download the completed project.
Download the complete project.
Overview of HTML Forms
HTML form Overview
HTML forms use either GET or POST to send data to the server.MethodAttribute ofFormElement gives the HTTP method:
HTML forms use GET or POST to send data to the server.FormElementMethodThe label attribute provides 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,EnctypeAttribute specifies the format of the request body:
The default method is GET. If the form uses GET, the form data is encoded into the URI as the query string. If form uses POST, form data is placed in the Request body. For POST data,EnctypeThe tag attribute specifies the Request body format:
Enctype |
Description 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. Form data is encoded into a "name/value" pair, similar to a URI query string. This is the default format of 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. Form data is encoded into multi-part MIME messages. This format is used to upload files to the server. |
MIME refers to Multipurpose Internet Mail Extensions-multi-purpose Internet Mail Extension, which is an Internet standard for transmitting Mail messages over the network. MIME specifies a symbolic method used to represent various data types. In the HTTP protocol, MIME is also used for the content type of the HTTP message to represent the data type. The preceding enctype label attribute indicates the encoding Type, which is used to specify the Content-Type (Content Type) header attribute of an HTTP message. The value specified for this label attribute must be one of the values specified by MIME for Content-Type. The above table shows two values about the content type in MIME. For more information, see MIME-related documents.
Part 1 of this article looks at x-www-form-urlencoded format. Part 2 describes multipart MIME.
Part 1 of this article examines the x-www-form-urlencoded format. Part 1 describes multi-part MIME.
Sending Complex Types
Send compound type
Typically, you will send a complex type, composed of values taken from several form controls. Consider the following model that represents a status update:
Typically, you want to send a composite type consisting of the values of several form controls. Consider a State update model as follows:
namespace FormEncode.Models
{
using System;
using System.ComponentModel.DataAnnotations;
public class Update
{
[Required]
[MaxLength(140)]
public string Status { get; set; }
public DateTime Date { get; set; }
}
}
Here is a Web API controller that accepts an Update object via POST.
The following is a Web API controller that receives Update objects through POST.
namespace FormEncode.Controllers
{
using FormEncode.Models;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
public class UpdatesController: ApiController
{
static readonly Dictionary <Guid, Update> updates = new Dictionary <Guid, Update> ();
[HttpPost]
[ActionName ("Complex")]
public HttpResponseMessage PostComplex (Update update)
{
if (ModelState.IsValid && update! = null)
{
// Convert any HTML markup in the status text.
// Convert HTML tags in status text.
update.Status = HttpUtility.HtmlEncode (update.Status);
// Assign a new ID.
// Assign a new ID.
var id = Guid.NewGuid ();
updates [id] = update;
// Create a 201 response.
// Create a 201 response.
var response = new HttpResponseMessage (HttpStatusCode.Created)
{
Content = new StringContent (update.Status)
};
response.Headers.Location =
new Uri (Url.Link ("DefaultApi", new {action = "status", id = id}));
return response;
}
else
{
return Request.CreateResponse (HttpStatusCode.BadRequest);
}
}
[HttpGet]
public Update Status (Guid id)
{
Update update;
if (updates.TryGetValue (id, out update))
{
return update;
}
else
{
throw new HttpResponseException (HttpStatusCode.NotFound);
}
}
}
}
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 ".
This controller uses "action-based routing (section 4.1-Translator's note in this series of tutorials)". Therefore, the routing template is "api/{controller}/{action}/{id }". The client submits the data to "/api/updates/complex ".
Now let's write an HTML form for users to submit a status update.
Now, let's write an HTML form for users to submit status updates.
<h1>Complex Type</h1> <form id="form1" method="post" action="api/updates/complex"
enctype="application/x-www-form-urlencoded"> <div>
<label for="status">Status</label>
</div>
<div>
<input name="status" type="text" />
</div>
<div>
<label for="date">Date</label>
</div>
<div>
<input name="date" type="text" />
</div>
<div>
<input type="submit" value="Submit" />
</div>
</form>
Notice thatActionAttribute on the form is the URI of our controller action. Here is the form with some values entered in:
Note:ActionThe label attribute is the URI of the controller action. The following are forms that have already entered some values:
Figure 5-6. Input some data forms
When the user clicks Submit, the browser sends an HTTP request similar to the following:
When a user clicks "Submit", the browser sends an HTML request similar to the following data:
POST http://localhost:38899/api/updates/complex HTTP/1.1
Accept: text/html, application/xhtml+xml, */*
User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0) Content-Type: application/x-www-form-urlencoded Content-Length: 47 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.
Note: The request body contains form data and is formatted as a "name/value" pair. The Web API automatically converts the "name/value" pair to an instance of the Update class.
Sending Form Data via AJAX
Send form data through 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.
When a user submits a form, the browser leaves the current page and renders the Response Message Body. This is okay when the response is an HTML page. However, for Web APIs, the response body is usually empty or structured data such as JSON. In this case, it makes more sense to use AJAX requests to send form data so that the page can process the response.
The following code shows how to post form data using jQuery.
The following code demonstrates how to use jQuery to submit form data.
<script type="text/javascript">
$("#form1").submit(function () {
var jqxhr = $.post('api/updates/complex', $('#form1').serialize())
.success(function () {
var loc = jqxhr.getResponseHeader('Location');
var a = $('<a/>', { href: loc, text: loc });
$('#message').html(a);
})
.error(function () {
$('#message').html("Error posting the update.");
});
return false;
});
</script>
The jQuerySubmitFunction replaces the form action with a new function. This overrides the default behavior of the Submit button.SerializeFunction serializes the form data into name/value pairs. To send the form data to the server, call$. Post ().
JQuerySubmitThe function replaces the form action with a new function. It overrides the default behavior of the Submit button.SerializeThe function serializes form data into a "name/value" pair. To send form data to the server, call$. Post ().
When the request completes,. Success ()Or. Error ()Handler displays an appropriate message to the user.
When the request is complete,. Success ()Or. Error ()The processor displays a message (see Figure 5-7 ).
Figure 5-7. Send form data through AJAX
Sending Simple Types
Simple sending type
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.
In the previous section, we sent a composite type, and the Web API will serialize it into a model class instance. You can also send simple types, such as strings.
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.
Before sending a simple type, consider encapsulating the value into a composite type. The advantage is that you can perform model verification on the server side and expand the model as necessary.
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 withFromBodyAttribute.
The basic steps for sending simple types are the same, but there are two minor differences. First, in the controller, you must useFromBodyAnnotation property to modify the parameter name.
[HttpPost]
[ActionName("Simple")]
public HttpResponseMessage PostSimple([FromBody] string value)
{
if (value != null)
{
Update update = new Update()
{
Status = HttpUtility.HtmlEncode(value),
Date = DateTime.UtcNow
};
var id = Guid.NewGuid();
updates[id] = update;
var response = new HttpResponseMessage(HttpStatusCode.Created)
{
Content = new StringContent(update.Status)
};
response.Headers.Location =
new Uri(Url.Link("DefaultApi", new { action = "status", id = id }));
return response;
}
else
{
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
By default, Web API tries to get simple types from the request URI.FromBodyAttribute tells Web API to read the value from the request body.
By default, Web APIs attempt to obtain simple types through the requested URI.FromBodyThe annotation property tells the Web API to read this value from the request body.
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.
The Web API can read the response body at most once, so only one parameter of the action can obtain the Request body. To obtain multiple values from the request body, you need to define a composite type.
Second, the client needs to send the value with the following format:
Second, the client needs to send this value in the following format:
=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:
In particular, the value section of the "name/value" pair must be empty for a simple type. Not all browsers support this format for HTML forms, but you have created the format in the script as follows:
$.post('api/updates/simple', { "": $('#status1').val() });
Here is an example form:
The following is an example form:
And here is the script to submit the form value. The only difference from the previous script is the argument passed intoPostFunction.
The following is a script for submitting form values. The only difference from the previous script is thatPostParameters passed in the function.