Search code examples
c#asp.netasp.net-mvcasp.net-mvc-4dynamic

Iterate through dynamic form object


Using mvc i get values like this to avoid class declarations and router changes.

public dynamic Create([FromBody] dynamic form)
{
    var username = form["username"].Value;
    var password = form["password"].Value;
    var firstname = form["firstname"].Value;
...

I like to iterate through all values and check them for null or empty.


Solution

  • If you get a json from the argument, you could convert it to an Dictionary<string, dynamic> where the string key is the name of the property and the dynamic is a value that can assume any type. For sample:

    var d = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(form);
    
    var username = d["username"];
    

    You also could loop between Keys property from the Dictionary<>:

    foreach(var key in d.Keys)
    {
       // check if the value is not null or empty.
       if (!string.IsNullOrEmpty(d[key])) 
       {
          var value = d[key];
          // code to do something with 
       }
    }