在 MVC 核心视图中显示计算
Display calculation in MVC Core View
我正在尝试在视图中显示百分比计算的结果。
Round 和 Score 来自本地数据库,我想计算记录的回合数,将存储在 Score 中的值相加,然后以百分比形式输出结果。我希望这是有道理的!
目前我在数据库中存储了一些值,但我得到的结果一直是零。来自数据库的值似乎没有进入计算方法。
在此先致谢!
控制器:
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);
}
型号:
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; }
}
查看:
@model EmailAndPDF_Test.Models.PracticeViewModel
<p> @Model.Percentage</p>
错误public INT百分比{ get;放; };您必须将其更改为 public DOUBLE Percentage { get;放; };
为什么改为 var rounds = _context.Practices3.Select(r => r.Round).Count();
你不使用 _context.Practices3.Count();也许你的意思是 _context.Practices3.Where(r => r.Round>0).Count();?
尝试代替 pvm.Percentage = scores / (rounds * 10) * 100;使用
pvm.Percentage = Math.Round((分数 / (轮数 * 10)) * 100,3);
我正在尝试在视图中显示百分比计算的结果。 Round 和 Score 来自本地数据库,我想计算记录的回合数,将存储在 Score 中的值相加,然后以百分比形式输出结果。我希望这是有道理的!
目前我在数据库中存储了一些值,但我得到的结果一直是零。来自数据库的值似乎没有进入计算方法。
在此先致谢!
控制器:
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);
}
型号:
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; }
}
查看:
@model EmailAndPDF_Test.Models.PracticeViewModel
<p> @Model.Percentage</p>
错误public INT百分比{ get;放; };您必须将其更改为 public DOUBLE Percentage { get;放; };
为什么改为 var rounds = _context.Practices3.Select(r => r.Round).Count(); 你不使用 _context.Practices3.Count();也许你的意思是 _context.Practices3.Where(r => r.Round>0).Count();?
尝试代替 pvm.Percentage = scores / (rounds * 10) * 100;使用 pvm.Percentage = Math.Round((分数 / (轮数 * 10)) * 100,3);