【发布时间】:2018-04-20 21:59:10
【问题描述】:
我正在尝试根据用户从下拉列表中选择的 tableName 来动态显示表格。我从我的网络控制器(.Net Core)传递一个 json 对象,所以为了做到这一点,我首先使用函数将我的 dataTable 转换为对象列表
public static List<T> ConvertTableToList<T>(this DataTable table) where T : class, new()
{
try
{
List<T> list = new List<T>();
foreach (var row in table.AsEnumerable())
{
T obj = new T();
foreach (var prop in obj.GetType().GetProperties())
{
try
{
PropertyInfo propertyInfo = obj.GetType().GetProperty(prop.Name);
propertyInfo.SetValue(obj, Convert.ChangeType(row[prop.Name], propertyInfo.PropertyType), null);
}
catch(Exception ex)
{
throw ex;
}
}
list.Add(obj);
}
return list;
}
catch
{
return null;
}
}
并在我的 Get Request 中调用此函数
public IActionResult GetTableDetailsByTableName(string TableNameSelected)
{
//To get the data for the Table Selected
DataTable TableDetails = ReferenceTableLogics.getTableDetails(TableNameSelected);
var TableDetailsInList = ConverterClass.ConvertTableToList<CSBM_AGE_BAND>(TableDetails);
return Ok(TableDetailsInList);
}
现在的问题是我需要根据用户在下拉列表中选择的内容 (TableNameSelected) 告诉我的班级名称(例如 CSBM_AGE_BAND)。
有什么方法可以动态地将这个类名传递给我的函数ConvertTableToList?
【问题讨论】:
-
使用反射,请看下面我的回答
-
如果我的回答对你有用,你能投票和/或评论吗?
标签: asp.net-core http-get generic-list