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