c# – 将NameValueCollection转换为动态对象
发布时间:2020-12-16 01:56:26 所属栏目:百科 来源:网络整理
导读:我试图将一个FormCollection传递给我的ASP.NET MVC控制器并将其转换为动态对象,然后将其序列化为Json并传递给我的Web API. [HttpPost] public ActionResult Create(FormCollection form) { var api = new MyApiClient(new MyApiClientSettings()); dynamic d
我试图将一个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的示例,但需要采用其他方式. 任何帮助,将不胜感激. 解决方法
一个快速的谷歌搜索出现了这个:
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"; 那是你在找什么? (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |