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.
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?
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