2011-01-07 4 views
7

안녕하세요, Request.Form을 매개 변수로 전달해야하지만 먼저 일부 키/값 쌍을 추가해야합니다. 나는 Collection이 읽기 전용이라는 예외를 가진다.Request.Form을 사전이나 다른 것으로 serialize하기

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을 : 지정된 캐스트가 아니다 유효한.

일부 도움, 누구? 고맙습니다

답변

15

stringstring으로 전송할 필요가 없습니다. 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; 
} 

그런 식으로 쉽게 갈 수 있습니다

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

thanx Matthew, 내일 시도 할 것입니다. 나는 숨겨진 들판들과 당분간 같이 갔다. –

+0

matthew - 좋은 +1 (및 +1). 스코틀랜드 인, 작은 LINQ를 사용하여 아래에서 나의 찔림에 저항 할 수 없었다 :). 새해 복 많이 받으세요 - parf ... :-) (btw, 블로그를 조금이라도 읽었으니 지금은 regula와 javascript linq 기사가 좋음) btw,이 자바 스크립트 LINQ 구현을 검토하고 싶을 수도 있습니다 http : //jslinq.codeplex .com/ –

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를 사용하는 모든 유지 한 줄에. 당신이 이미 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로 그것을 과장하지. 사실, 나는 램프 스택에 프로비저닝되어야하고 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); 
관련 문제