我正在尝试创建一种标准方法来处理基于 cookie 中存储的值填充视图模型,这些值用作搜索条件的用户默认值。
我在将字符串 cookie 值转换为属性类型时遇到问题,以便可以适当地更新视图模型。收到以下错误:
Invalid cast from 'System.String' to 'System.Reflection.RuntimePropertyInfo'.
这是我所拥有的:
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;
}