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