I'm wondering how to get dynamic obj from enum in my case:
For ex. I have some list of objects and I was iterating smth like this:
foreach(var case in Viewbag.Cases)
{
<tr>
<td>@case.Positive</td>
<td>@case.Negative</td>
</tr>
}
but I would use my enum where I have:
public enum ResultsEnum
{
[Display(Name = "POSITIVE")]
Positive = 1,
[Display(Name = "NEGATIVE")]
Negative
}
in that way:
foreach(var case in Viewbag.Cases)
{
foreach(var enumName in Enum.GetNames(typeof(ResultsEnum))
<tr>
<td>@case.Positive.@enumName</td>
<td>@case.Negative.@enumName</td>
</tr>
}
but after that the obj is not dynamic and here is my question:
is it possible to do iteration in that way?
Now my result isn't a record from DB but string case.Negative
You can use reflection to access the enum
values and then map them to properties in your case objects.
foreach (var caseObj in ViewBag.Cases)
{
<tr>
@foreach (var enumValue in Enum.GetValues(typeof(ResultsEnum)))
{
var enumName = Enum.GetName(typeof(ResultsEnum), enumValue);
var propertyInfo = caseObj.GetType().GetProperty(enumName);
var value = propertyInfo.GetValue(caseObj);
<td>@value</td>
}
</tr>
}