0

I have the following script in my ASP.NET MVC Core View:

window["dataSet1"] = [];

@foreach (var item in Model.SelectedOptions)
{
     foreach (var item2 in Model.MyChartData)
     {
          // ".mph" exists in 'MyChartData' model
          // This works... but it's not dynamic
          @:window["dataSet1"].push(['@item', @item2.mph);

          // How can I get a dynamic variable determine 
          // what field to retrieve from the model?
          // Example values for 'SelectedOptions' are: 
          //    > "mph", "kph", "m/s", "knots"
          // I'd like this to work...
          @:window["dataSet1"].push(['@item', @item2.@item);
     }
}

Instead of creating if else statements for each possible 'SelectedOptions' value (mph, kph, m/s, knots etc.), is it possible to simply use a variable to reference a specific object within my model?

The data I get back from my attempt is:

window["dataSet1"].push(['mph', MyProject.Models.MyChartData.mph]);

Rather than a value from my model, for example:

window["dataSet1"].push(['mph', 15.16451]);
Siguza
  • 21,155
  • 6
  • 52
  • 89
X22
  • 25
  • 9

2 Answers2

1

You can solve it in c# adding a property using reflection to get the value or a simple case

Example:

 @:window["dataSet1"].push(['@item', @item2.correctvalue( item );

In the item2 class:

 public decimal correctvalue( propName ) {
    return this.GetType().GetProperty(propName).GetValue(this, null);
 }

Or more simple:

 public decimal correctvalue( propName ) {
    if (propName = "mph") {
        return this.mph;
    }
    else ...
 }

Keep in mind that you should validate the propName or the reflection will error. More info on using reflection to get the property value

Community
  • 1
  • 1
Eduardo Molteni
  • 38,786
  • 23
  • 141
  • 206
  • Hi Eduardo. I am trying to get away from using if statements, as if new data is added, then the if statement needs updating. Therefore, is there another approach that can be made to strength the code? – X22 May 10 '16 at 12:45
  • Yes, use the first option – Eduardo Molteni May 10 '16 at 14:34
  • Thanks for your help, it certainly pointed me in the right direction. I will post the solution I created. – X22 May 11 '16 at 12:23
0

The solution I created, whilst whacking it into a static class so it can be easily accessed in future.

public static object GetPropertyValue(this object myProperty, string propertyName)
{
    return myProperty.GetType().GetProperties()
       .Single(pi => pi.Name == propertyName)
       .GetValue(myProperty, null);
}
halfer
  • 19,824
  • 17
  • 99
  • 186
X22
  • 25
  • 9