2015-11-11 35 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(""); 
    } 
}