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

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".

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="APICall.aspx.cs" Inherits="WebApplication1.APICall" %>  
<head runat="server">  
    <script src="jquery-1.7.1.js" type="text/javascript"></script>  
     <script>  
         $(document).ready(function () {  
             $("#Save").click(function () {  
                 $.ajax({  
                     url: 'http://localhost:3413/api/person?Name=Sourav',  
                     type: 'POST',  
                     dataType: 'json',  
                     success: function (data, textStatus, xhr) {  
                         console.log(data);  
                     },  
                     error: function (xhr, textStatus, errorThrown) {  
                         console.log('Error in Operation');  
                     }  
                 });  
             });  
         });  
    </script>  
</head>  
<body>  
    <form name="form1" id="form1">  
        <input type="button" id="Save" value="Save Data" />  
    </form>  
</body>  
</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.

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Net;  
using System.Net.Http;  
using System.Web.Http;  
  
namespace WebApplication1.WebAPI  
{  
    public class personController : ApiController  
    {  
        [HttpPost]  
        public String PostAction([FromUri] string Name)  
        {  
            return "Post Action";  
        }  
    }  
}

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.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="APICall.aspx.cs" Inherits="WebApplication1.APICall" %>  
<head runat="server">  
    <script src="jquery-1.7.1.js" type="text/javascript"></script>  
     <script>  
         $(document).ready(function () {  
             $("#Save").click(function () {  
                 $.ajax({  
                     url: 'http://localhost:3413/api/person',  
                     type: 'POST',  
                     dataType: 'json',  
                     data:{"":"Sourav Kayal"},  
                     success: function (data, textStatus, xhr) {  
                         console.log(data);  
                     },  
                     error: function (xhr, textStatus, errorThrown) {  
                         console.log('Error in Operation');  
                     }  
                 });  
             });  
         });  
    </script>  
</head>  
<body>  
        <input type="button" id="Save" value="Save Data" />  
</body>  
</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.

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Net;  
using System.Net.Http;  
using System.Web.Http;  
  
namespace WebApplication1.WebAPI  
{  
    public class person  
    {  
        public string name { get; set; }  
        public string surname { get; set; }  
    }  
    public class personController : ApiController  
    {  
        [HttpPost]  
        public String PostAction([FromBody] String Name)  
        {  
            return "Post Action";  
        }  
    }  
}

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:

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Net;  
using System.Net.Http;  
using System.Web.Http;  
  
namespace WebApplication1.WebAPI  
{  
    public class personController : ApiController  
    {  
        [HttpPost]  
        public String PostAction([FromBody]string name, [FromBody] string surname)  
        {  
            return "";  
        }  
    }  
}

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.


Similar Articles