2013-08-01 404 views
3

我想將FormCollection傳遞給我的ASP.NET MVC控制器並將其轉換爲動態對象,然後將其序列化爲Json並傳遞給我的Web API。將NameValueCollection轉換爲動態對象

[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"]; 
    } 

我見過的例子動態對象轉換成字典或NameValueValueCollection,但需要走另一條路。

任何幫助,將不勝感激。

+3

你能說你想達到什麼嗎? –

+1

我猜你是要求兩行代碼將集合變成ExpandoObject? –

+2

你在找這樣的事嗎? http://stackoverflow.com/a/7596697/187697 – keyboardP

回答

2

我已經展示瞭如何在下面創建和dynamic dictionary/keyvaluepair。我添加了一個擴展方法來將字典轉換爲NameValueCollection

這對我來說很好,但你應該知道的一件事是字典不允許重複鍵和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; 
    } 

}