Iterate through dynamic form object

43,580

Solution 1

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 
   }
}

Solution 2

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

var data = (IDictionary<string, object>)form;

Solution 3

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"]);
}
Share:
43,580

Related videos on Youtube

MR.ABC
Author by

MR.ABC

Updated on April 14, 2021

Comments

  • MR.ABC
    MR.ABC about 3 years

    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.

    • doctorlove
      doctorlove almost 10 years
      s/"I like to"/"I would like to, and don't know how" ?
    • Andrew Whitaker
      Andrew Whitaker almost 10 years
      You'd like to avoid class declarations? Why?
    • MR.ABC
      MR.ABC almost 10 years
      @doctorlove Maybe sound better. I'm not sure about your intentions. Go for foreach(var value in form).
    • Felipe Oriani
      Felipe Oriani almost 10 years
      Use DTO to get the input from Views. It is easy to implement
    • Chris
      Chris almost 10 years
      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?
    • MR.ABC
      MR.ABC almost 10 years
      @Andrew Whitaker because i work with javascript and json. This just overhead and make no sense.
    • Andrew Whitaker
      Andrew Whitaker almost 10 years
      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.
    • MR.ABC
      MR.ABC almost 10 years
      Just want make method to avoid write 10 times String.IsNullOrWhiteSpace. Something like HaveNullOrWhiteSpaceValues(form)
    • MR.ABC
      MR.ABC almost 10 years
      @Andrew Whitaker Believe me this fits better in my workflow.
  • MR.ABC
    MR.ABC almost 10 years
    No chance to test it yet but seems solid.
  • Dmitry Volkov
    Dmitry Volkov about 7 years
    that's just what I was looking for!
  • Jay
    Jay about 6 years
    Probably because of this: Message "Cannot convert type '<>f__AnonymousType0<string,string>' to 'System.Collections.Generic.IDictionary<string,object>'" str‌​ing.
  • Jay
    Jay about 6 years
    Should've tested it then, because it throws an exception.
  • xcopy
    xcopy about 6 years
    @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.
  • Jay
    Jay about 6 years
    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.
  • Eric Ferreira
    Eric Ferreira about 5 years
    Worked for me!!