Frazer Mountford Frazer Mountford - 3 months ago 14
ASP.NET (C#) Question

Reference an c# Object Field by its name passed as a string

I am writing a custom repoting module using ASP.NET MVC in C#

The user will be able to define a list of the fields they want to see in the report.

I would like to know if it is possible to reference a object field using a string, so that I can enumerate through the list of chosen fields.

for example normally in the view, quite basically I would do the following

@foreach (Title item in Model)
{
@item.Name
@item.Isbn
}


I would be looking for something like

@foreach (Title item in Model)
{
@item.Select("Name")
@item.Select("Isbn")
}

Answer

One of the ways to do that is through reflection. Add this helper method somewhere:

private object GetValueByPropertyName<T>(T obj, string propertyName)
{
    PropertyInfo propInfo = typeof(T).GetProperty(propertyName);

    return propInfo.GetValue(obj);
}

Usage:

@foreach (Title item in Model)
{
    var name =  GetValueByPropertyName(item, "Name");
    var isbn =  GetValueByPropertyName(item, "Isbn");
}
Comments