I'm trying to post form serialized values to controller (Web API Self Host). I cannot understand why the NameValueCollection is not correctly bound. Client-side using jQuery:
// Form Submit Handler
$( '#form-parameters' ).submit(function (event) {
event.preventDefault();
var formData = $(this).serialize();
// Post serialized form data
postAssemblyParameters(formData);
});
// Post Form Data to controller test
function postAssemblyParameters(formData){
$.ajax({
url: http://localhost/api/test/1,
type: 'POST',
data: formData,
dataType: 'application/x-www-form-urlencoded',
success: function(x3d) {
},
error: function(xhr) {
}
});
}
Server-side using Web API Self Host:
public void Post([FromUri] int id, [FromBody] NameValueCollection formData)
{
Console.WriteLine(id); // OK
// Collection is NULL
foreach (var key in formData.AllKeys)
{
foreach (var val in formData.GetValues(key))
{
Console.WriteLine(key + ": " + val);
}
}
}
Many thanks.
Thanks Scott. Your answer was just what I needed. Based on it, I wrote the following little utility method that will come in handy as it pulls all the data values out of the stream (using the FormDataCollection) and puts them into a NamedValueCollection (which you can access in any order you want).
/// <summary>
/// Copy the values contained in the given FormDataCollection into
/// a NameValueCollection instance.
/// </summary>
/// <param name="formDataCollection">The FormDataCollection instance. (required, but can be empty)</param>
/// <returns>The NameValueCollection. Never returned null, but may be empty.</returns>
public static NameValueCollection Convert(FormDataCollection formDataCollection)
{
Validate.IsNotNull("formDataCollection", formDataCollection);
IEnumerator<KeyValuePair<string, string>> pairs = formDataCollection.GetEnumerator();
NameValueCollection collection = new NameValueCollection();
while (pairs.MoveNext())
{
KeyValuePair<string, string> pair = pairs.Current;
collection.Add(pair.Key, pair.Value);
}
return collection
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With