http://www.binaryintellect.net/articles/589f6915-f4c0-4bf9-9f94-4d00bd445c16.aspx
This solution works perfectly fine.
I had an HTML form where all the input controls were dynamic. Had a hard time plumbing the form data to MVC controller and then again to Web Api 2 controller.
Your server side web api method needs to be like
public string Post(FormDataCollection form){
... }
FormDataCollection resides in System.Net.Http.Formatting namespace.
If you are posing data directly from a web page (jquery), then the above link solution is works fine.
If you posting data web page to an MVC page (c# code) which is then further posted to a web api method, then the code looks like this:
[HttpPost]
public async Task<string> MasterDraw(FormCollection body)
{
HttpClient client = new HttpClient();
KeyValuePair<string, string>[] list = null;
string url = ConfigurationManager.AppSettings["BaseServiceUrl"] + "/api/MasterOperation/addrecord";
if (body != null && body.HasKeys())
{
list = new KeyValuePair<string, string>[body.AllKeys.Count()];
for (int ctr = 0; ctr < body.Keys.Count; ctr++ )
{
list[ctr] = new KeyValuePair<string, string>(body.Keys[ctr], body.GetValue(body.Keys[ctr]).AttemptedValue);
}
}
var content = new FormUrlEncodedContent(list);
HttpResponseMessage response = await client.PostAsync(url, content);
// Check that response was successful or throw exception
response.EnsureSuccessStatusCode();
// Read response asynchronously as JToken and write out top facts for each country
string contentRes = response.Content.ReadAsStringAsync().Result;
return contentRes;
}
The browser side code:
$('#btn-save').on('click', function (event) {
var postUrl = "@Url.Action("masterdraw","masterrender")";
var result = $.ajax({
type: "POST",
data: $('#form').serialize(),
url: postUrl
});
// insert your jquery .done and .error methods
});