2011-01-07 13 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

stringをにキャストする必要はありません。 NameValueCollectionは、文字列のキーと文字列の値の周りに構築されます。どのように迅速な拡張メソッドについて:あなたは簡単に行くことができ

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; 
} 

その方法:

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を使用していますについてはどのように

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

thanxマシュー、私は明日それを試してみるつもりです。私は当分隠された畑に行った。 –

+0

matthew - 素晴らしいもの(そして+1)。スコットで、私の刺し傷に抵抗することができませんでした。幸せな新年 - parf ... :-)(btw、ちょうど今あなたのブログのちょっと読んでレギュラとjavascriptのlinq記事が好きです) btw、このJavaScriptのLINQ実装を見直したいかもしれませんhttp://jslinq.codeplex .com/ –

1

アンドレ、

1行にあなたはすでにMVCを使用している場合、あなたは0行でそれを行うことができます

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

シンプルに保つ、ええ? :) – jgauffin

+0

喜喜、エイ::)私は時々linqでそれをやり過ごします。実際には、私はLAMPスタックにプロビジョニングされなければならない新しい機会が提供されているので、私はジレンマを持っており、linqなしでphp5オブジェクトにどのように対処するのだろうと思っています:) (tho私はこのhttpを見ました://phplinq.codeplex.com/) –

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

:これは、の拡張メソッドにexrapolatedすることができコードの

using System.Web.Mvc; 

var dictionary = new Dictionary<string, object>(); 
Request.Form.CopyTo(dictionary); 
関連する問題