Iterate through dynamic form object
Asked Answered
T

4

31

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.

Troll answered 19/8, 2014 at 13:42 Comment(9)
s/"I like to"/"I would like to, and don't know how" ?Hircine
You'd like to avoid class declarations? Why?Soledadsolely
@Hircine Maybe sound better. I'm not sure about your intentions. Go for foreach(var value in form).Troll
Use DTO to get the input from Views. It is easy to implementAphasic
What exactly are you wanting to iterate over? The actual properties of your object or does it have an indexer and you just want to check all the things that are indexed?Whereof
@Andrew Whitaker because i work with javascript and json. This just overhead and make no sense.Troll
If you were create a class to represent your incoming form, you could leverage ASP.NET MVC's built in validation and possibly avoid the overhead you're incurring by using dynamic here.Soledadsolely
Just want make method to avoid write 10 times String.IsNullOrWhiteSpace. Something like HaveNullOrWhiteSpaceValues(form)Troll
@Andrew Whitaker Believe me this fits better in my workflow.Troll
A
42

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 
   }
}
Aphasic answered 19/8, 2014 at 13:54 Comment(3)
No chance to test it yet but seems solid.Troll
Should've tested it then, because it throws an exception.Creatine
Worked for me!!Lebron
P
15

This is quite old, but I came across this and am wondering why the following was not proposed:

var data = (IDictionary<string, object>)form;
Peephole answered 1/3, 2017 at 16:48 Comment(4)
that's just what I was looking for!Thorrlow
Probably because of this: Message "Cannot convert type '<>f__AnonymousType0<string,string>' to 'System.Collections.Generic.IDictionary<string,object>'" string.Creatine
@Jay, if you are receiving that message, you are not casting against a dynamic object but instead trying to cast against an anonymous type which is not the same thing.Peephole
I ran the statement with 'dynamic form', just like in the OP. I ended up converting my dynamic to json with JsonConvert and then JsonConverting my json to a Dictionary<string, object>. That works fine for me.Creatine
A
2

You can use JavaScriptSerializer and dynamic object:

JavaScriptSerializer serializer = new JavaScriptSerializer();

dynamic myDynamicObject = serializer.DeserializeObject(json);

For example, if you want to loop through myDynamicObject["users"]:

foreach (KeyValuePair<string, dynamic> user in myDynamicObject["users"]){
    Console.WriteLine(user.Key+": "+user.Value["username"]);
    Console.WriteLine(user.Key+": "+user.Value["email"]);
}
Aglimmer answered 14/4, 2018 at 12:7 Comment(0)
V
0

the answers above did not work for me, but that works:

//responseBody is a json string with "settings" key
dynamic dynamicObject = JsonConvert.DeserializeObject<dynamic>(responseBody)!;
var settings = dynamicObject.settings;

var k = 0;
foreach (JProperty item in settings.Children())
    Console.WriteLine($"{k++}. settings - {item.Name}: {item.Value}");
Vivienviviene answered 4/5, 2023 at 14:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.