5

I am attempting to create a standard method to handle populating a view model based on stored values in a cookie, that are used as user defaults for search criteria.

I am having issues when it comes to converting the string cookie values to the property type so the view model can be updated appropriately. Getting the following error:

Invalid cast from 'System.String' to 'System.Reflection.RuntimePropertyInfo'.

Here is what I have:

public TViewModel GetUserSearchCriteriaDefaults<TViewModel>(TViewModel viewModel)
        where TViewModel : class
{
    Type type = viewModel.GetType();
    string className = viewModel.GetType().Name;
    PropertyInfo[] properties = type.GetProperties();

    if (Request.Cookies[className] != null)
    {
        string rawValue;

        foreach (PropertyInfo property in properties)
        {
            if (!String.IsNullOrEmpty(Request.Cookies[className][property.Name]))
            {
                rawValue = Server.HtmlEncode(Request.Cookies[className][property.Name]);
                Type propertyType = property.GetType();
                var convertedValue = Convert.ChangeType(rawValue, propertyType); <---- Error from this line
                property.SetValue(viewModel, convertedValue);
            }
        }
    }

    return viewModel;
}
1
  • I see that you're trying to make this super generic, but it would seem that this would only allow you to store a single instance of any class in the cookie. This may fit your needs at first glance but kinda defeats the purpose of being super generic imo. Why not just create a string to view model adapter for the classes that you need, then maybe use a factory to dig them out of your cookies? It would be more "intentional" (for lack of a better term) and less prone to ...weirdness? Commented Jul 17, 2013 at 15:31

1 Answer 1

12

change

Type propertyType = property.GetType();

to

Type propertyType = property.PropertyType;

Using GetType(), you get the type of property. And property is an instance of PropertyInfo.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.