[英]Get all properties from a view model to display in array
我有一個具有很多屬性的視圖模型,我創建了一個自定義屬性來將數據發送到 hubspot,因為 hubspot 需要一個特定的命名法,然后我需要創建一個具有迭代器之王的方法,該方法適用於每個屬性包含我的自定義屬性的他放了一個特定的輸出,這是代碼:
public class CreateTrialUserHubspotViewModel {
[HubspotAttribute("firstname")]
[Display(Name = "First Name")]
[StringLength(50)]
[Required]
public string FirstName { get; set; }
[HubspotAttribute("lastname")]
[Display(Name = "Last Name")]
[StringLength(50)]
[Required]
public string LastName { get; set; }
[HubspotAttribute("jobtitle")]
[Display(Name = "Job title")]
[StringLength(50)]
[Required]
public string JobTitle { get; set; }
}
現在這是我的自定義屬性
[AttributeUsage(AttributeTargets.All)]
public class HubspotAttribute : System.Attribute {
public readonly string hubspotValue;
public HubspotAttribute(string value)
{
this.hubspotValue = value;
}
}
然后我需要創建一個方法來獲取一個視圖模型對象並創建我的輸出,我需要一些關於如何做到這一點的建議,將是這樣的:
private static RowValidation ValidateRowWithManifest<T>(CreateTrialUserHubspotViewModel trialUser) {
RowValidation validation = new RowValidation();
FieldInfo[] fields = typeof(T).GetPropertiesOfSomeWay;
foreach (DataType field in fields) {
output+=whatINeed
}
return validation;
}
}
所需的輸出將類似於:[firstname:"pepe", lastname="perez", jobtitle"none"]。 只需調用該方法將返回我需要的所有數據。
public string GetString<T>(T @object)
{
var output = new StringBuilder();
var type = typeof(T);
var properties = type.GetProperties();
foreach (var property in properties)
{
var attributes = property.GetCustomAttributes(typeof(HubspotAttribute), true);
if (attributes.Length == 0)
continue;
var name = ((HubspotAttribute)attributes[0]).hubspotValue;
var value = property.GetValue(@object) ?? "none";
output.AppendFormat("{0}:\"{1}\",", name, value);
}
var fields = output.ToString().TrimEnd(',');
return string.Format("[{0}]", fields);
}
如果您正在尋找將屬性連接成一個看起來像 JSON 字符串的字符串(這將是處理它的更好方法)的東西,您可以使用以下內容:
private static string CreateOutput(CreateTrialUserHubspotViewModel trialUser)
{
var properties = trialUser.GetType().GetProperties().Where(x => Attribute.IsDefined(x, typeof(HubspotAttribute))).ToList();
var values = properties.Select(x =>
{
var att = x.GetCustomAttribute(typeof(HubspotAttribute));
var key = ((HubspotAttribute)att).hubspotValue;
var val = x.GetValue(trialUser);
return $"{key}:{val}";
});
var sb = new StringBuilder();
values.ToList().ForEach(v =>
{
sb.Append(v);
if (values.Last() != v) sb.Append(',');
});
return sb.ToString();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.