4

我正在尝试将 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 的示例,但需要采用其他方式。

任何帮助,将不胜感激。

4

2 回答 2

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

那是你要找的吗?

于 2013-08-01T21:58:36.653 回答
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;
    }

}
于 2013-08-01T22:21:14.457 回答