user585440
user585440

Reputation:

How to access subproperties of property from variable name

I want to modify a property in List in a model. Because there are many such list, I use reflection GetType().GetProperty(propertyName) to do it as follows,

public class SalesViewModel
{
public List<SelectListItem> SourceTypes0 { get; set; }
...
public List<SelectListItem> SourceTypes9 { get; set; }
}

SalesViewModel model = new SalesViewModel();
model.SourceTypes0 = from r in this._repository.SourceTypes
                    select new SelectListItem
                    {
                        Text = r.Name,
                        Value = SqlFunctions.StringConvert((double)r.SourceTypeID)
                    }).OrderBy(c => c.Text).ToList();
...
model.SourceTypes9 = from r in this._repository.SourceTypes
                    select new SelectListItem
                    {
                        Text = r.Name,
                        Value = SqlFunctions.StringConvert((double)r.SourceTypeID)
                    }).OrderBy(c => c.Text).ToList();

for (int i = 0; i < 10; i++)
{
string propertyName = "SourceTypes" + i.ToString();
var propInfo = model.GetType().GetProperty(propertyName);
if (propInfo != null)
{
propInfo.SetValue(model, "...", null);
}
}

If I want to modify model.SourceTypes0[1].Selected field, the problem is how to cast propInfo to List or access SourceTypes0[1].Selected. I try

List<SelectListItem> propInfo = (List<SelectListItem>)model.GetType().GetProperty(propertyName);

But it gives error as

Cannot convert System.Reflection.PropInfo to System.Collections.Generic.List<System.Web.Mvc.SelectListItem>

I need help on this. Thanks.

Upvotes: 0

Views: 67

Answers (1)

M4N
M4N

Reputation: 96576

The method GetProperty() returns a PropertyInfo. If you want to get the value of that property, you need to call its GetValue() method:

var propInfo = model.GetType().GetProperty(propertyName);
var theList = (List<SelectListItem>)propInfo.GetValue(model);

Upvotes: 2

Related Questions