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


[HttpPost]
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) {
    $.ajax({
        type: "POST",
        url: url,
        data: data,
        dataType: 'html',
        success: function (response) {
            console.log("PostData::success");
            callback(response);
        },
        failure: function (response) {
            console.log("PostData::failure");
            callback(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.