C# 用模型对象替换Html中的占位符
我很难解释我到底想做什么。它可能有个名字,但我不知道它是什么。 首先,我有一个模型,例如:C# 用模型对象替换Html中的占位符,c#,reflection,C#,Reflection,我很难解释我到底想做什么。它可能有个名字,但我不知道它是什么。 首先,我有一个模型,例如: public class Customer { public int Id { get; set; } public int ProductId { get; set; } ...more properties... public virtual Product Product { get; set; } } public class Pr
public class Customer
{
public int Id { get; set; }
public int ProductId { get; set; }
...more properties...
public virtual Product Product { get; set; }
}
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
...more properties...
}
其次,我在{}
中有一个带有占位符的HTML文本字符串。我希望有类似于{Id}
的东西,并让它用模型属性替换Html文本
名称{Id}-{Product.Name}
我的想法是使用NameValueCollection将模型属性作为字符串获取。使用反射,我可以对基本属性执行此操作,但不能对Product.Name
之类的内容执行此操作
我走错方向了吗?我可以使用什么来获取一个NameValueCollection,以循环使用它并替换Html
以下是我的当前代码(跳过虚拟属性):
这应该是递归的,但似乎应该有更好的方法。顺便说一句,我不需要专门的
NameValueCollection
(例如可以是Dictionary
)。思想?是否有一个nuget包已经做到了这一点?我最终只是使用了我所拥有的,并添加了一个子部分来处理子对象。我不想做完全递归,因为我只想要直接的子对象,而不是整个链
public virtual NameValueCollection GetNameValueCollection(Object obj)
{
Type type = obj.GetType();
PropertyInfo[] properties = type.GetProperties();
var coll = new NameValueCollection();
foreach (PropertyInfo property in properties)
{
if(!property.GetGetMethod().IsVirtual)
{
if (property.PropertyType == typeof(DateTime))
{
var date = (DateTime)property.GetValue(obj, null);
coll.Add(property.Name, date.ToLongDateString());
}
else if (property.PropertyType == typeof(DateTime?))
{
var date = (DateTime?)property.GetValue(obj, null);
if (date.HasValue)
{
coll.Add(property.Name, date.Value.ToLongDateString());
}
else
{
coll.Add(property.Name, string.Empty);
}
}
else
{
var value = property.GetValue(obj, null);
if (value != null)
{
coll.Add(property.Name, value.ToString());
}
}
}
}
return coll;
}