12

我正在尝试将表单序列化值发布到控制器(Web API Self Host)。我不明白为什么 NameValueCollection 没有正确绑定。使用 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) {

                }
        });
}

使用 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);
                }
        }
}

非常感谢。

4

3 回答 3

25

尝试使用 FormDataCollection,而不是 NameValueCollection。

http://weblogs.asp.net/cibrax/archive/2012/08/10/binding-form-data-in-asp-net-web-api.aspx

于 2013-03-02T05:29:27.157 回答
5

或者您可以使用构建“ReadAsNameValueCollection”,如下所示:

NameValueCollection MyNameValueCollection = formData.ReadAsNameValueCollection();
于 2015-06-24T07:30:46.847 回答
4

谢谢斯科特。你的回答正是我所需要的。在此基础上,我编写了以下小实用程序方法,它将派上用场,因为它将所有数据值从流中提取出来(使用 FormDataCollection)并将它们放入 NamedValueCollection(您可以按您想要的任何顺序访问)。

/// <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
 }
于 2014-10-15T23:03:25.510 回答