Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a NameValueCollection to a dynamic object [closed]

Tags:

c#

asp.net-mvc

I am trying to take a FormCollection passed to my ASP.NET MVC Controller and convert it to a dynamic object, which is then serialized as Json and passed to my 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"];
    }

I've seen examples converting a dynamic object to a Dictionary or NameValueValueCollection, but need to go the other way.

Any help would be appreciated.

like image 1000
mattruma Avatar asked Mar 23 '23 22:03

mattruma


1 Answers

A quick google search turned up this:

http://theburningmonk.com/2011/05/idictionarystring-object-to-expandoobject-extension-method/

So you can do:

IDictionary<string, string> dict = new Dictionary<string, string> { { "Foo", "Bar" } };
dynamic dobj = dict.ToExpando();
dobj.Foo = "Baz";

Is that what you are looking for?

like image 54
Steve Czetty Avatar answered Apr 06 '23 06:04

Steve Czetty