Jan 14, 2016

How to send an object and a parameter to an asp.net web api

In this sample we will post an object and a string parameter with ajax from client. Asp.net side will recognize data as form data. We will convert (deserialize) coming object data into corresponding class.

  • Server side: Webapi function

public string WebapiPost()
    var httpRequest = HttpContext.Current.Request;

    string name = httpRequest.Form["name"];
    string jsonObj = httpRequest.Form["obj"];

    JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
    MyObject obj = jsonSerializer.Deserialize<MyObject>(jsonObj);

    return obj.Key;


public class MyObject
    public int ID { get; set; }
    public string Key { get; set; }


  • Client side: Post function 

function PostDataSample(url, data) {
        type: "POST",
        url: url,
        data: data,
        dataType: 'html',
        success: function (response) {
        failure: function (response) {

Note that "dataType" is "html"

  • Client side: Call post function

var name = "Oktay";
var myObject = {};
myObject.ID = 1;
myObject.Key = "key1";

PostDataSample("/api/postMyobject/WebapiPost", "obj=" + JSON.stringify(myObject) + "&name=" + name, "html");
Note that we used object as JSON.stringify. You can add more parameters.