ASP. NET Web API Tutorial 5.2 Sending HTML form data: URL-encoded form data

Source: Internet
Author: User



Note: This article is part of the ASP. NET Web API Series tutorial, if this is the first time you've seen this series of tutorials, look at the previous section first.


5.2 Sending HTML Form Data
5.2 Sending HTML form data


This article quoted: http://www.asp.net/web-api/overview/working-with-http/sending-html-form-data,-part-1



by Mike wasson| June 15, 2012
Mike Wasson | Date: 2012-6-15


Part 1:form-urlencoded Data
Part 1th: 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
      An overview of HTML forms
    • Sending Complex Types
      Send composite type
    • Sending Form Data via AJAX
      Send form data via Ajax
    • Sending Simple Types
      Send Simple Type


Download the completed project.
Download the full project.


Overview of HTML Forms
An 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:
HTML forms use Get or post to send data to the server. The method label property of the form element gives the HTTP methods:


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:
The default method is get. If the form uses get, the form data is encoded into the URI as a query string. If the form uses post, the form data is placed in the request body. For post data, theenctype Tag property indicates the format of the request body:


enctype Description
Describe
application/x-www-form-urlencoded Form data is encoded as name/value pairs, and similar to a URI query string. The default format for POST.
form data is encoded as a "first name/value" pair, 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. The use of this format if is uploading a file to the server.
The form data is encoded into a multi-part MIME message. If the file is uploaded to the server, this format is used.


MIME refers to Multipurpose Internet Mail extensions-Multi-purpose Internet Message extension, which is an Internet standard for delivering mail messages over the network. MIME defines a symbolic method for representing various data types. In the HTTP protocol, the content type of the HTTP message also uses the MIME method of representing the data type. The enctype tag attribute above means "encoding type", which is used to specify the Content-type (content Type) header property of the HTTP message. The value specified for this label property must be one of the values set by MIME for Content-type. In the table above, there are two values for the content type in MIME. For more information, please refer to the MIME data-translator note



Part 1 of this article looks at x-www-form-urlencoded format. Part 2 describes multipart MIME.
The 1th part of this article examines the x-www-form-urlencoded format. Part 2nd describes multipart mime.


Sending Complex Types
Send composite type


Typically, you'll 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 that consists of the values of several form controls. Consider the following model that represents a status update:


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, this accepts an Update object via POST.
The following is a Web API controller that receives the update object via 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 the HTML markup in the 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 and so the route template is "Api/{controller}/{action}/{id}". The client would post the data to "/api/updates/complex".
This controller uses the "action-based routing (section 4.1 of this tutorial series-translator Note)", so the routing template is "Api/{controller}/{action}/{id}". The client will submit the data to "/api/updates/complex".



Now let's write an HTML form for the users to submit a status update.
Now, let's write an HTML form where the user submits the status update.


 
<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 that, the action attribute on the form are the URI of our controller action. Here's the form with some values entered in:
Note that the action Tag property of the form is the URI of the controller action. Here are the forms that have entered some values:



Figure 5-6. A form with some data entered



When the user clicks Submit, the browser sends a HTTP request similar to the following:
When the user clicks "Submit", the browser sends an HTML request similar to the following data:


content-type:application/x-www-form-urlencoded 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 that the request body contains the form data and is formatted as a "first name/value" pair. The Web API automatically translates the "First name/value" pair into an instance of the update class.


Sending Form Data via AJAX
Send 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 are an HTML page. With a web API, however, the response body is usually either empty or contains structured data, such as JSON. In this case, it makes more sense to send the form data using a AJAX request, so the page can process the response.
When the user submits the form, the browser leaves the current page and renders the response message body. This is fine 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 send the form data with an AJAX request so that the page can handle the response.



The following code shows how to post form data using JQuery.
The following code shows how to submit form data in jquery.


 <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 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 ().
The submit function of jquery replaces the action of the form with a new function. It overrides the default behavior of the Submit button. The serialize function serializes the form data into a "first name/value" pair. To send the form data to the server, call $.post ().



When the request completes, the . Success () or . Error () handler displays a appropriate message to the US Er.
When the request is complete, the. Success () or . Error () processor displays a corresponding message to the user (see Figure 5-7).



Figure 5-7. Send form data via Ajax


Sending Simple Types
Send Simple 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 would 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 your benefits of model validation on the server side, and makes it easier to extend your model if needed.
Before you send a simple type, consider encapsulating the value as a composite type. The benefit is that you can perform model validation on the server side and extend the model if necessary.



The basic steps to send a simple type is the same, but there is the subtle differences. First, the controller, you must decorate the parameter name with the frombody attribute.
The basic steps for sending a simple type are the same, but there are two subtle differences. First, in the controller, you must use the frombody annotation property to decorate the parameter name.


 [HttpPost] [ActionName ("simple")] public httpresponsemessage postsimple ([Frombody] string value) {if (Value! = N             ull) {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 Stringconte NT (update.         Status)}; Response.         Headers.location = new Uri (Url.link ("Defaultapi", new {action = "status", id = id});     return response;     } else {return request.createresponse (httpstatuscode.badrequest); }
[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. The frombody attribute tells Web API to read the value from the request body.
By default, the Web API attempts to get a simple type from the requested URI. The frombody annotation property tells the Web API to read this value from the request body.



Web API reads the response body at most once, so is only one parameter of a 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 reads the response body one at a time, so only one parameter of the action can be obtained from the request body. If you need to get 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 is empty for a simple type. Not all browsers the support the this for HTML forms, but you create the this format in script as follows:
In particular, the value portion of the "name/value" pair must be empty for the 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's an example form:


<h1>Simple Type</h1> 
<form id="form2"> 
    <div> 
        <label for="status">Status</label> 
    </div> 
    <div> 
        <input id="status1" type="text" /> 
    </div> 
    <div> 
        <input type="submit" value="Submit" /> 
    </div> 
</form>

The following is a sample form:



And here are the script to submit the form value. The only difference from the previous script was the argument passed into the post function.
The following is a script that submits the form values. The only difference from the previous script is the arguments passed in the post function.

<h1>Simple Type</h1> 
<form id="form2"> 
    <div> 
        <label for="status">Status</label> 
    </div> 
    <div> 
        <input id="status1" type="text" /> 
    </div> 
    <div> 
        <input type="submit" value="Submit" /> 
    </div> 
</form>


You can use the same approach to send a array of simple types:
You can send an array of simple types in the same way:


{"": ["Update One", "Update One", "Update Three"]});


Additional Resources
Other resources
Part 2: File Upload and Multipart MIME
Part 2: File Upload and Multipart MIME Formats (Section 5.3 of this series of tutorials - Translator's Note)

 

If you feel that there is something to gain after reading this article, please give a recommendation.

Reference page:

http://www.yuanjiaocheng.net/CSharp/csharphuanjing.html

http://www.yuanjiaocheng.net/CSharp/Csharp-jagged-array.html

Http://www.yuanjiaocheng.net/mvc/htmlhelper-validationsummary.html

http://www.yuanjiaocheng.net/CSharp/csharp-partial-class.html

http://www.yuanjiaocheng.net/CSharp/Csharp-Exception.html

Http://www.yuanjiaocheng.net/webapi/webapi-filters.html

Http://www.yuanjiaocheng.net/entity/tixijiegou.html

Http://www.yuanjiaocheng.net/entity/entitytypes.html

http://www.yuanjiaocheng.net/CSharp/Csharp-queue.html

http://www.yuanjiaocheng.net/webapi/Consume-web-api.html

http://www.yuanjiaocheng.net/ASPNET-CORE/core-identity-migrations.html

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.