2011-01-07 26 views
7

嗨,我需要通過我的Request.Form作爲參數,但首先我必須添加一些鍵/值對。我收到了該集合是隻讀的例外。序列化Request.Form字典或其他

我已經試過:

System.Collections.Specialized.NameValueCollection myform = Request.Form; 

,我也得到了同樣的錯誤。

,我已經試過:

foreach(KeyValuePair<string, string> pair in Request.Form) 
{ 
    Response.Write(Convert.ToString(pair.Key) + " - " + Convert.ToString(pair.Value) + "<br />"); 
} 

測試,如果我可以通過一個到另一個字典傳遞一個,但我得到:

System.InvalidCastException:指定 投不有效。

有些幫助,有人嗎? Thanx

回答

15

您無需投下stringstringNameValueCollection圍繞字符串鍵和字符串值構建。怎麼樣快速的擴展方法:

public static IDictionary<string, string> ToDictionary(this NameValueCollection col) 
{ 
    var dict = new Dictionary<string, string>(); 

    foreach (var key in col.Keys) 
    { 
    dict.Add(key, col[key]); 
    } 

    return dict; 
} 

這樣,你可以輕鬆地去:

var dict = Request.Form.ToDictionary(); 
dict.Add("key", "value"); 
+0

thanx馬修,我明天去試試。我暫時與隱藏的領域。 – 2011-01-07 02:37:01

+0

馬修 - 很好的(和+1)。作爲一個scot,忍不住用下面的LINQ來刺激我下面的這個:)。新年快樂 - parf ... :-)(btw,稍微閱讀一下你的博客,喜歡regula和javascript linq文章) btw,你可能想要回顧一下這個javascript LINQ實現http://jslinq.codeplex .com/ – 2011-01-07 10:47:56

1

安德烈,

怎麼樣:

System.Collections.Specialized.NameValueCollection myform = Request.Form; 

IDictionary<string, string> myDictionary = 
    myform.Cast<string>() 
      .Select(s => new { Key = s, Value = myform[s] }) 
      .ToDictionary(p => p.Key, p => p.Value); 

使用LINQ to保持它的所有在一條線上。這可能是exrapolated到的擴展方法:

public static IDictionary<string, string> ToDictionary(this NameValueCollection col) 
{ 
    IDictionary<string, string> myDictionary = new Dictionary<string, string>(); 
    if (col != null) 
    { 
     myDictionary = 
      col.Cast<string>() 
       .Select(s => new { Key = s, Value = col[s] }) 
       .ToDictionary(p => p.Key, p => p.Value); 
    } 
    return myDictionary; 
} 

希望這有助於..

+0

保持簡單,eeh? :) – jgauffin 2011-01-07 10:28:22

+0

嘻嘻,啊 - :)。我有時會用linq過度。事實上,我有一個困境,因爲我已經提供了一個新的機會,必須在LAMP堆棧上供應,並且想知道我將如何應對php5對象而不需要LINQ :) (我確實看到了這個http ://phplinq.codeplex.com/) – 2011-01-07 10:44:18

3
public static IEnumerable<Tuple<string, string>> ToEnumerable(this NameValueCollection collection) 
{ 
    return collection 
     //.Keys 
     .Cast<string>() 
     .Select(key => new Tuple<string, string>(key, collection[key])); 
} 

public static Dictionary<string, string> ToDictionary(this NameValueCollection collection) 
{ 
    return collection 
     //.Keys 
     .Cast<string>() 
     .ToDictionary(key => key, key => collection[key])); 
} 
9

如果您已經使用MVC,然後你可以用零線做的代碼。

using System.Web.Mvc; 

var dictionary = new Dictionary<string, object>(); 
Request.Form.CopyTo(dictionary);