问题
In my MVC5 application I have table lets's say it's name is Student and every student belonging to a Team. I want to show students according to their teams by percentage. For this reason I also created a ViewModel in order to join Student entity with Team entity. So, how can I show the data I want on Kendo UI pie chart? Could you have a look at the code and correct the mistakes below? And could you give a View samples suitable to this approach? Thanks in advance.
ViewModel:
public class StudentViewModel
{
public int StudentId { get; set; }
public int TeamId { get; set; }
public string TeamName { get; set; }
public int TeamPercentage { get; set; }
}
Controller:
public ActionResult Index_Read([DataSourceRequest] DataSourceRequest request)
{
var dataContext = repository.Student;
var result = dataContext.ToDataSourceResult(request, m => new StudentViewModel
{
StudentId = m.StudentId,
TeamId = m.TeamId,
TeamName = m.TeamName,
TeamPercentage = //??? How can I obtain percentage by Lambda Expression ???
}
);
return Json(result, JsonRequestBehavior.AllowGet);
}
回答1:
You could do something like this:
Viewmodel
public class StudentViewModel
{
public string category { get; set; }
public int value { get; set; }
}
Controller (note I've made some assumptions in the query)
public ActionResult Index_Read()
{
var teamCount = repository.Team.Count();
var result = repository.Student.GroupBy(g => g.TeamName).Select(s => new StudentViewModel { category = s.Key, value = s.Count()/teamCount });
// Imagine result contains something like this: { category = "Team 1", value = "20" }, { category = "Team 2", value = "30" }, { category = "Team 3", value = "10" }, { category = "Team 4", value = "40" }
return View(result);
}
View
@model IEnumerable<StudentViewModel>
@(Html.Kendo().Chart()
.Name("chart")
.Title(title => title.Text("Teams").Position(ChartTitlePosition.Bottom))
.Legend(legend => legend.Visible(true))
.Series(series => series.Pie(Model))
)
Alternative
Another way to do it would be using a data source binding.
public class StudentViewModel
{
public string TeamName{ get; set; }
public int Percentage { get; set; }
}
@(Html.Kendo().Chart<StudentViewModel>()
.Name("chart2")
.DataSource(ds => ds.Read("GetTeamData", "Home"))
.Series(series => series.Pie(m => m.Percentage, model => model.TeamName))
)
来源:https://stackoverflow.com/questions/28897992/showing-data-by-percentage-on-pie-charts-in-mvc