我正在尝试将FormCollection传递给我的ASP.NET MVC Controller并将其转换为动态对象,然后将其序列化为Json并传递给我的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"];
}
我见过将动态对象转换为Dictionary或NameValueValueCollection的示例,但需要采用其他方式。
任何帮助都将不胜感激。
答案 0 :(得分:5)
快速谷歌搜索出现了这个:
http://theburningmonk.com/2011/05/idictionarystring-object-to-expandoobject-extension-method/
所以你可以这样做:
IDictionary<string, string> dict = new Dictionary<string, string> { { "Foo", "Bar" } };
dynamic dobj = dict.ToExpando();
dobj.Foo = "Baz";
这就是你要找的东西吗?
答案 1 :(得分:2)
我已经展示了如何在下面创建和dynamic dictionary/keyvaluepair
。我添加了一个扩展方法,将字典转换为NameValueCollection
。
这对我来说效果很好,但你应该注意的一点是,Dictionary不允许重复键,而NameValueCollection
也是如此。如果您尝试移动到词典,那么可能会抛出异常。
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;
}
}