【发布时间】:2018-09-27 07:23:43
【问题描述】:
我有一个包含模型显示名称字符串的列表:
public class TVSystemViewData : BaseViewData
{
[Display(Name = "AccountId", Description = "")]
public String AccountId { get; set; }
[Display(Name = "AllocatedManagedMemory", Description = "")]
public String AllocatedManagedMemory { get; set; }
[Display(Name = "AllocatedPhysicalMemory", Description = "")]
public String AllocatedPhysicalMemory { get; set; }
[Display(Name = "AudioMute", Description = "")]
public String AudioMute { get; set; }
}
我需要使用 foreach 循环设置属性以将值添加到我的模型:
这是从 POST 应用程序获取值的方式
var model.AccountId = shell.getParameter("AccountId")
var model.AllocatedManagedMemory = shell.getParameter("AllocatedManagedMemory");
shell.GetParameter 从 POST 中获取值。
这就是我想要的: 我有一个获取所有显示属性的方法
public List<String> GetTVSystemProperties()
{
return typeof(TVSystemViewData)
.GetProperties()
.SelectMany(x => x.GetCustomAttributes(typeof(DisplayAttribute), true) //select many because can have multiple attributes
.Select(e => ((DisplayAttribute)e))) //change type from generic attribute to DisplayAttribute
.Where(x => x != null).Select(x => x.Name) //select not null and take only name
.ToList();
}
我的收藏是一个字符串列表 例如:集合 {"AccountId","AllocatedManagedMemory"...}
我的模型是 TVSystemViewData
foreach (item in collection)
{
if(item == modelProperty name){
// i don know how
model.property = shell.getParameter(item)
}
}
[更新] 我正在使用这个:
foreach (var property in UtilsHandler.getConfigAsList("sysDataSource"))
{
//Set Values to Model
try
{
model.GetType().GetProperty(property).SetValue(model, shell.getParameter(property), null);
}
catch (Exception)
{
Have issue with data types
}
}
我对数据类型有疑问。 但我使用一个 foreach 循环。 仍在寻找最佳方法
【问题讨论】:
-
我不确定我是否理解这个问题。您正在编写自定义模型绑定器吗?
标签: c# c#-4.0 data-annotations