dayanrr91 dayanrr91 - 2 months ago 10
ASP.NET (C#) Question

Get all properties from a view model to display in array

I have a view model that have a lot of properties, and I created a custom attribute for send the data to hubspot, because hubspot need a specific nomenclature, then I need to create a method that have some king of iterator, that for every property that contain my custom attribute he put a specific output, here is the code:

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; }
}


Now this is my custom attribute

[AttributeUsage(AttributeTargets.All)]
public class HubspotAttribute : System.Attribute {
public readonly string hubspotValue;

public HubspotAttribute(string value)
{
this.hubspotValue = value;
}
}


And then I need to create a method that take a viewmodel object and create my output, I need some suggest about how to do that, will be something like this:

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;
}
}


The needed output will be like: [firstname:"pepe", lastname="perez", jobtitle"none"]. just calling that method will return all the data I need.

Answer

If you are looking for something that will concatenate properties into a string that looks like a JSON string (and that would be a better way to handle it), you can use something like the following:

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 = att.GetType().GetField("hubspotValue").GetValue(att);
        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();
}