我必须从未知的实体获取属性的类型,然后将字符串值解析为传递给操作的字符串值。
代码示例:
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]]'."}
我采用了ataravati的解决方案,并对其进行了一些修改,以使用可空类型。
解决方法如下:
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
if (propertyInfo != null)
{
var type = Nullable.GetUnderlyingType(propertyInfo.PropertyType) ?? propertyInfo.PropertyType;
var safeValue = (value == null) ? null : Convert.ChangeType(value, type);
propertyInfo.SetValue(pext, safeValue, null);
}
Db.SaveChangesWithHistory(LoggedEmployee.EmployeeId);
return Content("");
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句