我的问题是回应: Showing System.Web.Helpers.Chart in a partial view from the model
@{
var myChart = new Chart(width: 600, height: 400)
.AddTitle("Chart Title")
.AddSeries(
name: "Employee",
xValue: new[] { "Peter", "Andrew", "Julie", "Mary", "Dave" },
yValues: new[] { "2", "6", "4", "5", "3" })
.Write();
}
是否有人能够在xValue和yValue中使用循环中的值。目前在示例中,我发现所有值都是硬编码的。
我想将item.season用作X和item.year作为下面foreach语句中的Y(第一个聚集主题,第二个收集年份和季节):
string json2 = File.ReadAllText(@"C:\Temp\Assess.json");
var root = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<List<WebApplication1.Models.SchoolSubject>>(json2);
foreach (var subject in root)
{
<h2>@Html.Raw(subject.Subject)</h2>
foreach (var item in subject.AppScores)
{
<p>@Html.Raw(item.Season)</p>
<p>@Html.Raw(item.year)</p>
<p>@Html.Raw(item.value)</p>
}
}
包含类代码的模型:
public class SchoolSubjectAppScore
{
public string Season { get; set; }
public string year { get; set; }
public string value { get; set; }
}
public class SchoolSubject
{
public SchoolSubject() { this.AppScores = new List<SchoolSubjectAppScore>(); }
public string Subject { get; set; }
public List<SchoolSubjectAppScore> AppScores { get; set; }
}
我拥有的JSON文件是:
[{"Subject": "English","AppScores": [{"Season": "Winter","year": "2009", "value" : "20" }, {"Season": "Summer","year": "2009", "value" : "38"}]}, {"Subject": "Maths","AppScores": [{"Season": "Winter","year": "2009", "value" : "10"}, {"Season": "Summer","year": "2009", "value" : "27"}]}]
我希望图表上的输出是两个系列 - 数学/英语,xValue - 季节/年和y值 - 值。
任何想法,因为我到处都寻求帮助。
答案 0 :(得分:1)
这很容易。您只需要在循环中将year
和List
数据从json添加到List
。获得string json2 = File.ReadAllText(@"C:\Temp\Assess.json");
var root = new System.Web.Script.Serialization.JavaScriptSerialize().Deserialize<List<WebApplication1.Models.SchoolSubject>>(json2);
var seasons = new List<string>();
var years = new List<string>();
foreach (var subject in root)
{
<h2>@Html.Raw(subject.Subject)</h2>
foreach (var item in subject.AppScores)
{
<p>@Html.Raw(item.Season)</p>
<p>@Html.Raw(item.year)</p>
seasons.Add(item.Season);
years.Add(item.year);
}
}
后,您可以将其转换为数组并将其分配给图表。请参阅下面的更新代码。
seasons
完成上述操作后,您可以将years
和@{
var myChart = new Chart(width: 600, height: 400)
.AddTitle("Chart Title")
.AddSeries(
name: "Employee",
xValue: seasons.ToArray(),
yValues: years.ToArray())
.Write();
}
添加到图表中。
{{1}}