Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate through dynamic form object

Tags:

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.

like image 470
MR.ABC Avatar asked Aug 19 '14 13:08

MR.ABC


2 Answers

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     } } 
like image 80
Felipe Oriani Avatar answered Oct 18 '22 15:10

Felipe Oriani


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

var data = (IDictionary<string, object>)form; 
like image 38
xcopy Avatar answered Oct 18 '22 16:10

xcopy