Setting class properties from NameValueCollection

I encrypt the entire query string on one page, and then decrypt it on another. I get a NameValueCollection of all values ​​using HttpUtility.ParseQueryString.

Now I have a class whose properties match the string character names of the request. I am trying to set the value of properties from a query string.

Here is my code:

NameValueCollection col = HttpUtility.ParseQueryString(decodedString); ConfirmationPage cp = new ConfirmationPage(); for(int i = 0; i < col.Count; i++) { Type type = typeof(ConfirmationPage); FieldInfo fi = type.GetField(col.GetKey(i)); } 

I see patterns of extracting values ​​through reflection - but I would like to get a link to the property of the ConfirmationPage class and set it with its value in the loop - col.Get (i).

+4
source share
2 answers

I would probably go the other way and find the properties (or fields using GetFields ()) and look for them in the query parameters, rather than iterating over the query parameters. Then you can use the SetValue method for the PropertyInfo object to set the property value on the ConfirmationPage page.

 var col = HttpUtility.ParseQueryString(decodedString); var cp = new ConfirmationPage(); foreach (var prop in typeof(ConfirmationPage).GetProperties()) { var queryParam = col[prop.Name]; if (queryParam != null) { prop.SetValue(cp,queryParam,null); } } 
+4
source

Try:

 typeof(ConfirmationPage).GetProperty(col.GetKey(i)) .SetValue(cp, col.Get(i), null); 
+2
source

Source: https://habr.com/ru/post/1343674/


All Articles