我的 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);
}
}
是否可以简单地使用变量来引用模型中的特定对象,而不是为每个可能的“SelectedOptions”值(mph、kph、m/s、knots 等)创建 if else 语句?
我从尝试中得到的数据是:
window["dataSet1"].push(['mph', MyProject.Models.MyChartData.mph]);
而不是我的模型中的值,例如:
window["dataSet1"].push(['mph', 15.16451]);
最佳答案
您可以在 C# 中解决这个问题,使用反射添加一个属性来获取值或一个简单的case
示例:
@:window["dataSet1"].push(['@item', @item2.correctvalue( item );
在 item2 类中:
public decimal correctvalue( propName ) {
return this.GetType().GetProperty(propName).GetValue(this, null);
}
或者更简单:
public decimal correctvalue( propName ) {
if (propName = "mph") {
return this.mph;
}
else ...
}
请记住,您应该验证 propName,否则反射将出错。 More info on using reflection to get the property value
关于javascript - 使用 View 动态访问模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37137919/