开发者

Setting a classes' properties from NameValueCollection

开发者 https://www.devze.com 2023-02-16 15:41 出处:网络
I\'m encrypting my entire query string on one page, then decrypting it on another.I\'m getting a NameValueCollection of all the values using HttpUtility.ParseQueryString.

I'm encrypting my entire query string on one page, then decrypting it on another. I'm getting a NameValueCollection of all the values using HttpUtility.ParseQueryString.

Now, I have a class whose properties match the query string variable names. I'm struggling how to set the value of the properties from the query string.

Here is my cod开发者_StackOverflow社区e in progress:

        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'm seeing samples of retrieving values through reflection - but I'd like to get a reference to the property of the ConfirmationPage class and set it with it's value in the loop - col.Get(i).


I would probably go the other way and find the properties (or fields using GetFields()) and look them up in the query parameters rather than iterate over the query parameters. You can then use the SetValue method on the PropertyInfo object to set the value of the property on the ConfirmationPage.

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


Try:

typeof(ConfirmationPage).GetProperty(col.GetKey(i))
                        .SetValue(cp, col.Get(i), null);
0

精彩评论

暂无评论...
验证码 换一张
取 消