将NameValueCollection转换为动态对象

本文关键字:动态 对象 转换 NameValueCollection | 更新日期: 2023-09-27 18:25:48

我正在尝试将FormCollection传递到我的ASP.NET MVC控制器,并将其转换为动态对象,然后将其序列化为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的例子,但需要走另一条路。

如有任何帮助,我们将不胜感激。

将NameValueCollection转换为动态对象

一个快速的谷歌搜索结果是:

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

这就是你要找的吗?

我在下面展示了如何创建和dynamic dictionary/keyvaluepair。我添加了一个扩展方法来将字典转换为NameValueCollection

这对我来说效果很好,但有一点你应该注意,Dictionary不允许重复键,NameValueCollection允许。因此,如果您尝试移动到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;
    }
}