2011-01-07 12 views
7

Hola necesito pasar mi Request.Form como un parámetro, pero primero tengo que añadir algunos pares clave/valor a la misma. Obtengo la excepción de que la Colección es de solo lectura.números de serie a Request.Form a un diccionario o algo

He intentado:

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

y me sale el mismo error.

y he intentado:

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

para probar si puedo pasar uno por uno a otro diccionario, pero me sale:

System.InvalidCastException: especificado yeso no es válido.

un poco de ayuda, alguien? Gracias

Respuesta

15

No es necesario echar una string a string. NameValueCollection se basa en claves de cadena y valores de cadena. ¿Qué tal un método de extensión rápida:

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

De esa manera usted puede ir fácilmente:

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

gracias Mateo, voy a intentarlo mañana. Fui con campos ocultos por el momento. –

+0

matthew - nice one (y +1). siendo un scot, no pude resistir mi puñalada en este debajo utilizando un pequeño LINQ :). feliz año nuevo - PARF ... :-) (por cierto, quien tiene lectura de su blog hace un momento, le gustaba la regula y javascript artículos LINQ) por cierto, es posible que desee revisar este Javascript LINQ aplicación http: //jslinq.codeplex .com/ –

1

Andre,

¿qué tal:

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

utiliza LINQ para mantener todo en una 'línea'. esto podría ser exrapolated a un método de extensión de:

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

esperanza esto ayuda ..

+0

manténlo simple, ¿eh? :) – jgauffin

+0

jejeje, sí - :). a veces me exagero con linq. de hecho, tengo un dilema, ya que me han ofrecido una nueva oportunidad que tiene que aprovisionarse en la pila LAMP y me pregunto cómo voy a hacer frente a los objetos php5 sin linq :) (aunque vi este 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])); 
} 

o

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

Si su ya utilizar MVC, entonces puede hacerlo con 0 líneas de código.

using System.Web.Mvc; 

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