4

I am trying to take a FormCollection passed to my ASP.NET MVC Controller and convert it to a dynamic object, which is then serialized as Json and passed to my Web API.

    [HttpPost]
    public ActionResult Create(FormCollection form)
    {
        var api = new MyApiClient(new MyApiClientSettings());

        dynamic data = new ExpandoObject();

        this.CopyProperties(form, data); // I would like to replace this with just converting the NameValueCollection to a dynamic

        var result = api.Post("customer", data);

        if (result.Success)
            return RedirectToAction("Index", "Customer", new { id = result.Response.CustomerId });

        ViewBag.Result = result;

        return View();
    }

    private void CopyProperties(NameValueCollection source, dynamic destination)
    {
        destination.Name = source["Name"];
        destination.ReferenceCode = source["ReferenceCode"];
    }

I've seen examples converting a dynamic object to a Dictionary or NameValueValueCollection, but need to go the other way.

Any help would be appreciated.

mattruma
  • 16,589
  • 32
  • 107
  • 171

2 Answers2

5

A quick google search turned up this:

http://theburningmonk.com/2011/05/idictionarystring-object-to-expandoobject-extension-method/

So you can do:

IDictionary<string, string> dict = new Dictionary<string, string> { { "Foo", "Bar" } };
dynamic dobj = dict.ToExpando();
dobj.Foo = "Baz";

Is that what you are looking for?

Steve Czetty
  • 6,147
  • 9
  • 39
  • 48
2

I have shown how to create and dynamic dictionary/keyvaluepair below. I have add an extension method to convert a dictionary to a NameValueCollection.

This works quite well for me but one thing you should be aware of is that Dictionary does not allow duplicate keys and NameValueCollection does. So that could throw an exception if you tried moving to a Dictionary.

void Main()
{
    dynamic config = new ExpandoObject();
    config.FavoriteColor = ConsoleColor.Blue;
    config.FavoriteNumber = 8;
    Console.WriteLine(config.FavoriteColor);
    Console.WriteLine(config.FavoriteNumber);

    var nvc = ((IDictionary<string, object>) config).ToNameValueCollection();
    Console.WriteLine(nvc.Get("FavoriteColor"));
    Console.WriteLine(nvc["FavoriteNumber"]);
    Console.WriteLine(nvc.Count);
}

public static class Extensions
{
    public static NameValueCollection ToNameValueCollection<TKey, TValue>(this IDictionary<TKey, TValue> dict)
    {
        var nvc = new NameValueCollection();
        foreach(var pair in dict)
        {
            string value = pair.Value == null ? null : value = pair.Value.ToString();
            nvc.Add(pair.Key.ToString(), value);
        }

        return nvc;
    }

}
phillip
  • 2,618
  • 19
  • 22