在MVC Core视图中显示计算

时间:2020-11-04 17:54:13

标签: c# entity-framework-core asp.net-core-mvc percentage

我正在尝试在视图中显示百分比计算的结果。 回合和分数来自本地数据库,我想计算记录的回合数,将分数中存储的值相加,然后以百分比形式输出结果。我希望这是有道理的!

当前,我在数据库中存储了一些值,但是我一直得到的结果是零。来自数据库的值似乎没有进入计算方法。

非常感谢!

控制器:

list2[high]

型号:

    public ActionResult CalcPercent()
    {
        PracticeViewModel pvm = new PracticeViewModel();
        
        var rounds = _context.Practices3.Select(r => r.Round).Count();
        var scores = _context.Practices3.Sum(s => s.Score);
        pvm.Percentage = scores / (rounds * 10) * 100;

        return View(pvm);
    }

ViewModel:

public class Practice
{
    [Key]
    public int Id { get; set; }
    public DateTime Date { get; set; }
    public int Score { get; set; }
    public double Round { get; set; }

}

查看:

public class PracticeViewModel
{
    public int Percentage { get; set; }
}

1 个答案:

答案 0 :(得分:1)

错误的公共INT百分比{组; };您必须将其更改为公开的DOUBLE Percentage {组; };

为什么改为var rounds = _context.Practices3.Select(r => r.Round).Count(); 您不使用_context.Practices3.Count();也许你的意思是_context.Practices3.Where(r => r.Round> 0).Count();?

尝试代替pvm.Percentage =得分/(回合* 10)* 100;使用 pvm.Percentage = Math.Round((分数/(回合* 10))* 100,3);