【问题标题】:Convert a NameValueCollection to a dynamic object [closed]将 NameValueCollection 转换为动态对象 [关闭]
【发布时间】:2013-08-03 00:49:59
【问题描述】:

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

任何帮助将不胜感激。

【问题讨论】:

标签: c# asp.net-mvc


【解决方案1】:

我在下面展示了如何创建和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;
    }

}

【讨论】:

    【解决方案2】:

    快速谷歌搜索发现:

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

    这就是你要找的吗?

    【讨论】:

    • 是的...只需要先将NameValueCollection转换为Dictionary即可。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-15
    • 2016-08-02
    • 1970-01-01
    • 1970-01-01
    • 2012-12-22
    相关资源
    最近更新 更多