2015-11-11 34 views
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]]'."} 
+0

尝试设置Convert.ChangeType(值,propertyInfo.PropertyType)作为的SetValue –

+2

的第二个参数,此代码看起来相当危险,它可以让你设置你的模型的任何财产。 – DavidG

回答

0

我采用了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(""); 
    } 
} 
0

试试这个(不过,作为DavidG在评论中提到,这使你可以设置的任何财产上的型号,这不是一个好主意):

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, Convert.ChangeType(value, propertyInfo.PropertyType), null); 

     Db.SaveChangesWithHistory(LoggedEmployee.EmployeeId); 

     return Content(""); 
    } 
}