4

ASP.NET MVC コントローラーに渡された FormCollection を動的オブジェクトに変換しようとしています。動的オブジェクトは 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

これは私にとっては非常にうまく機能しますが、注意すべきことの 1 つは、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 に答える