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.
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 } }
This is quite old, but I came across this and am wondering why the following was not proposed:
var data = (IDictionary<string, object>)form;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With