Web API With AJAX: Submit Form Data After Serialization

You are enjoying the "Web API with AJAX" article series. Here we are talking all about AJAX functionality associated with the Web API. Already we have covered many useful concepts on that, you can read them here.

In this article we will learn one very important concept in ajax() functionality. In day-to-day project development the common task is to submit form data to the server, in other words in the broad sense, "save user's data to server".  The data sending or data passing operation can be done in various ways, we can take data from an individual control and form it in JSON format or we can serialize an entire form's data and send it to the server.

The first technique is preferable when we don't want to send all data, we will collect the necessary data and after performing business operations and filtering, we will send it in JSON (or other) format. This is the first scenario.

In the second scenario, the operation is very straight-forward. We will serialize form data using the JavaScript's serialize() method and we will send it. In our next example we will implement this mechanism.
 
Send Form data after serialization

Here is the code for the client part. The code is pretty simple. In the body part we have defined a form with two text boxes and using the ajax() function the data is represented as form serialized data.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="APICall.aspx.cs" Inherits="WebApplication1.APICall" %>

<head id="Head1" 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: $('#form1').serialize(),

            success: function (data, textStatus, xhr) {

                console.log(data);

            },

            error: function (xhr, textStatus, errorThrown) {

                console.log(textStatus);

            }

        });

    });

});

    </script>

</head>

<body>

    <form name="person" id="form2">

        Name:- <input type="text"  name="name" id="name" />

        Surname:-<input type="text"  name="surname" id="surname" />

        <input type="button" id="Save" value="Save Data" />

    </form>

</body>

</html>

 
This is the implementation of the Web API part. The interesting thing to be noted is that, we have defined a person class within the Web API controller (if you don't like this way then you are allowed to implement a separate Model class) and the two properties of the person class enjoying the same name with the name attribute of the client form. Here is the code implementation.

 

using System;

using System.Collections.Generic;

using System.Collections.Specialized;

using System.Linq;

using System.Net;

using System.Net.Http;

using System.Net.Http.Formatting;

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(person form)

        {

            return form.name + form.surname;

        }

    }

}
 

That's fine; it's time to run the application. We are halting the application within the controller and we are seeing that the data has come from the client part.

Send Form data after serialization
 
Here is the output logged by the success method within the ajax() function.

logged by success method
Same scenario, another solution

In this example we will implement the same scenario another way. One very nice class the MVC class library is called "FormDataCollection". Here we will use this class to collect all serialized form data. This is the sample client code as in the previous example.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="APICall.aspx.cs" Inherits="WebApplication1.APICall" %>

<head id="Head1" runat="server">

    <title></title>

    <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: $('#form1').serialize(),

            success: function (data, textStatus, xhr) {

                console.log(data);

            },

            error: function (xhr, textStatus, errorThrown) {

                console.log(textStatus);

            }

        });

    });

});

    </script>

</head>

<body>

    <form name="form1" id="form2">

        Name:- <input type="text"  name="name" id="name" />

        Surname:-<input type="text"  name="surname" id="surname" />

        <input type="button" id="Save" value="Save Data" />

    </form>

</body>

</html>

Ok, we are done with the client setting (though there was nothing special there), here we will implement the Web API part. Have a look that we did not define any class or model class here. We are just using "FormDataCollection" to collect all serialized form data.
 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Net.Http;

using System.Net.Http.Formatting;

using System.Web.Http;

 

namespace WebApplication1.WebAPI

    public class personController : ApiController

    {

        [HttpPost]

        public string PostAction(FormDataCollection form)

        {

            return form.Get("name") + form.Get("surname");

        }

    }

}

When we use "FormDataCollection", we need to use the Get() method with a control name (HTML control) as the key value. Here is the output of the above example.

FormDataCollection

GetValues() function to get multi-valued control

That's fine, we are getting a value from a single-valued control. But what is the solution for a multi-valued control like radio button set, checkbox set and so on. Here is the solution for that.

In the client part we have implemented one form with a few checkboxes and we will send this from after serialization.
 

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="APICall.aspx.cs" Inherits="WebApplication1.APICall" %>

<head id="Head1" 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: $('#form1').serialize(),

            success: function (data, textStatus, xhr) {

                console.log(data);

            },

            error: function (xhr, textStatus, errorThrown) {

                console.log(textStatus);

            }

        });

    });

});

    </script>

</head>

<body>

    <form name="form1" id="form2">

        <input type="checkbox" name="chk" value="Check1" />Check 1

        <input type="checkbox" name="chk" value="Check2" />check 2

        <input type="checkbox" name="chk" value="Check3" />Check 3

        <input type="button" id="Save" value="Save Data" />

    </form>

</body>

</html>


The simple client code is finished, we will now implement the Web API part to get a value from all checkboxes. Oh! It's not rocket science. Just use one array and get it done. Still confused? This is for you.
 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Net.Http;

using System.Net.Http.Formatting;

using System.Web.Http;

 

namespace WebApplication1.WebAPI

{

    public class personController : ApiController

    {

        [HttpPost]

        public string[] PostAction(FormDataCollection form)

        {

            string[] values = form.GetValues("chk");

            return values;

        }

    }

}

We are halting our application to check the value within the action (though it's not necessary, but I am in the habit of checking, Ha..Ha..)

check the value within action

Here is the output within the success function of the ajax() method.

ajax method

Conclusion

If those methods are new to you then I hope you are eagerly waiting to implement them in your next application. Use then and smile when the data comes in the Web API end.


Similar Articles