Web API With AJAX: Understand FormBody and FormUri Attribute In Web API

This article exlains the FormBody and FormUri attributes and how to use them with an action parameter to consume data at the client end.

This is the "Web API with AJAX" article series. In this series we are explaining various ways to consume the Web API's RESTful services using jQuery ajax() and other methods. You can read our previous presentation by visiting the following articles:
This article exlains the "FormBody" and "FormUri" attributes and how to use them with an action parameter to consume data at the client end. So, let's learn by example.
 
Use of FromUri attribute to send data
 
Using the FormUri attribute, we can pass data through a URI/URL. The value should in the form of a key value pair. Here is one example to send data through a URI. In this example we are sending one string through the URL. The name of the parameter is "Name".
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="APICall.aspx.cs" Inherits="WebApplication1.APICall" %>  
  2. <head runat="server">  
  3.     <script src="jquery-1.7.1.js" type="text/javascript"></script>  
  4.      <script>  
  5.          $(document).ready(function () {  
  6.              $("#Save").click(function () {  
  7.                  $.ajax({  
  8.                      url: 'http://localhost:3413/api/person?Name=Sourav',  
  9.                      type: 'POST',  
  10.                      dataType: 'json',  
  11.                      success: function (data, textStatus, xhr) {  
  12.                          console.log(data);  
  13.                      },  
  14.                      error: function (xhr, textStatus, errorThrown) {  
  15.                          console.log('Error in Operation');  
  16.                      }  
  17.                  });  
  18.              });  
  19.          });  
  20.     </script>  
  21. </head>  
  22. <body>  
  23.     <form name="form1" id="form1">  
  24.         <input type="button" id="Save" value="Save Data" />  
  25.     </form>  
  26. </body>  
  27. </html>  
It's obvious that there are certain limitations in this method. The length of the URL in some browsers is limited to 256 characters and there might be a security loophole.
 
Configure Web API to get data from URI
 
Now we need to configure the Web API to extract data from a URI. We have implemented one action named "PostAction" that will take one parameter and the parameter is specified with the FromUri attribute. This implies that the value of the Name parameter will pass through the URI. Here is the implementation of the working code.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net;  
  5. using System.Net.Http;  
  6. using System.Web.Http;  
  7.   
  8. namespace WebApplication1.WebAPI  
  9. {  
  10.     public class personController : ApiController  
  11.     {  
  12.         [HttpPost]  
  13.         public String PostAction([FromUri] string Name)  
  14.         {  
  15.             return "Post Action";  
  16.         }  
  17.     }  
  18. }  
We have a halting application to check whether the data is coming and it's coming.
 
Note: We can pass multiple parameters in a single URI.
 
 
Get data using FromBody attribute
 
This is another way to get data in an ajax() call. In this example we will see how to get data using the FromBody attribute. Have a look at the following example.
 
Here is an Implementation of the ajax() function to send data. Have a look at the data parameter of the ajax() function. We are seeing that the data is being passed using a key value pair but the key portion is empty. When we are interested in receiving data using a FormBody attribute then we should keep the key section as empty.
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="APICall.aspx.cs" Inherits="WebApplication1.APICall" %>  
  2. <head runat="server">  
  3.     <script src="jquery-1.7.1.js" type="text/javascript"></script>  
  4.      <script>  
  5.          $(document).ready(function () {  
  6.              $("#Save").click(function () {  
  7.                  $.ajax({  
  8.                      url: 'http://localhost:3413/api/person',  
  9.                      type: 'POST',  
  10.                      dataType: 'json',  
  11.                      data:{"":"Sourav Kayal"},  
  12.                      success: function (data, textStatus, xhr) {  
  13.                          console.log(data);  
  14.                      },  
  15.                      error: function (xhr, textStatus, errorThrown) {  
  16.                          console.log('Error in Operation');  
  17.                      }  
  18.                  });  
  19.              });  
  20.          });  
  21.     </script>  
  22. </head>  
  23. <body>  
  24.         <input type="button" id="Save" value="Save Data" />  
  25. </body>  
  26. </html>  
Now we need to configure the Web API action to receive the value using the FromBody attribute. See the "PostAction" action in the person controller. We will see that the Name parameter is specified with the FromBody attribute.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net;  
  5. using System.Net.Http;  
  6. using System.Web.Http;  
  7.   
  8. namespace WebApplication1.WebAPI  
  9. {  
  10.     public class person  
  11.     {  
  12.         public string name { getset; }  
  13.         public string surname { getset; }  
  14.     }  
  15.     public class personController : ApiController  
  16.     {  
  17.         [HttpPost]  
  18.         public String PostAction([FromBody] String Name)  
  19.         {  
  20.             return "Post Action";  
  21.         }  
  22.     }  
  23. }  
 
We are seeing that the value is coming from the ajax() function at the time of the POST operation.
 
Is multiple FormBody attribute is allowed?
 
No, multiple formBodys is not allowed in a single action. In other words, we cannot specify multiple FromBody parameters in a single action. Here is an example of an incorrect implementation of an action:
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net;  
  5. using System.Net.Http;  
  6. using System.Web.Http;  
  7.   
  8. namespace WebApplication1.WebAPI  
  9. {  
  10.     public class personController : ApiController  
  11.     {  
  12.         [HttpPost]  
  13.         public String PostAction([FromBody]string name, [FromBody] string surname)  
  14.         {  
  15.             return "";  
  16.         }  
  17.     }  
  18. }  
Conclusion
 
This article has exlaind the concept of a FromUri and FromBody to receive a value from the jQuery ajax() function. I hope you have understood it and you will implement it in your next AJAX call. In a future article we will explore a few more interesting facts.