0
我必须从未知的实体中获取属性的类型,然后将字符串值解析为我传递给该操作的值。ASP.NET MVC C#实体转换为未知类型的未知属性
代码示例:
public ActionResult QuickEdit(int pk, string name, string value)
{
var pext = Db.ProjectExtensions.Find(pk);
if (ModelState.IsValid)
{
var propertyInfo = pext.GetType().GetProperty(name); //get property
propertyInfo.SetValue(pext, value, null); //set value of property
Db.SaveChangesWithHistory(LoggedEmployee.EmployeeId);
return Content("");
}
}
不幸的是,它仅在属性为字符串类型的作品。我如何解析值为我设置值的属性的类型?
谢谢!
更新:
我想:
propertyInfo.SetValue(pext, Convert.ChangeType(value, propertyInfo.PropertyType), null);
,我也得到
{"Invalid cast from 'System.String' to 'System.Nullable`1[[System.Double, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]'."}
尝试设置Convert.ChangeType(值,propertyInfo.PropertyType)作为的SetValue –
的第二个参数,此代码看起来相当危险,它可以让你设置你的模型的任何财产。 – DavidG