Hi i need to pass my Request.Form as a parameter, but first i have to add some key/value pairs to it. I get the exception that the Collection is readonly.
I've tried:
System.Collections.Specialized.NameValueCollection myform = Request.Form;
and i get the same error.
and i've tried:
foreach(KeyValuePair<string, string> pair in Request.Form)
{
Response.Write(Convert.ToString(pair.Key) + " - " + Convert.ToString(pair.Value) + "<br />");
}
to test if i can pass it one by one to another dictionary, but i get:
System.InvalidCastException: Specified cast is not valid.
some help, anyone? Thanx
You don't need to cast a string
to string
. NameValueCollection
is built around string keys, and string values. How about a quick extension method:
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;
}
That way you can easily go:
var dict = Request.Form.ToDictionary();
dict.Add("key", "value");
If your already using MVC then you can do it with 0 lines of code.
using System.Web.Mvc;
var dictionary = new Dictionary<string, object>();
Request.Form.CopyTo(dictionary);
Andre,
how about:
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);
uses LINQ to keep it all on one 'line'. this could be exrapolated to an extension method of:
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;
}
hope this helps..
public static IEnumerable<Tuple<string, string>> ToEnumerable(this NameValueCollection collection)
{
return collection
//.Keys
.Cast<string>()
.Select(key => new Tuple<string, string>(key, collection[key]));
}
or
public static Dictionary<string, string> ToDictionary(this NameValueCollection collection)
{
return collection
//.Keys
.Cast<string>()
.ToDictionary(key => key, key => collection[key]));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With