ASP.NET MVC#实体转换为未知属性的未知类型
我必须从未知的实体中获取属性的类型,然后解析传递给操作的字符串值 代码示例:ASP.NET MVC#实体转换为未知属性的未知类型,c#,asp.net,asp.net-mvc,linq,C#,Asp.net,Asp.net Mvc,Linq,我必须从未知的实体中获取属性的类型,然后解析传递给操作的字符串值 代码示例: public ActionResult QuickEdit(int pk, string name, string value) { var pext = Db.ProjectExtensions.Find(pk); if (ModelState.IsValid) { var propertyInfo = pext.GetType().GetProperty(name); //
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("");
}
}
不幸的是,只有当属性的类型为string时,它才起作用。如何将值解析为要为其设置值的属性的类型
谢谢
更新:
我试过:
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]]'."}
试试这个(然而,正如DavidG在评论中提到的,这让您可以在模型上设置任何属性,这不是一个好主意):
我采用了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("");
}
}
尝试将Convert.ChangeType(value,propertyInfo.PropertyType)设置为setValue的第二个参数。这段代码看起来非常危险,它允许您在模型上设置任何属性。
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("");
}
}