【发布时间】:2021-06-03 08:51:05
【问题描述】:
作为大学作业的一部分,尝试创建一个计算我网站的卡路里的运行总计。一切都完成了,除了这一部分,它一直让我绊倒。从理论上讲,它应该接受一个值并将其添加到运行总计中并显示该总计,但我认为每次按下按钮来计算它时,它都会运行一个我用来计算它的模型的新实例。此操作有 3 个文件相互交互
-
CalorieCount.cs - 包含数据和计算的模型
using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel.DataAnnotations; namespace BlairMackenzie_CalorieCount.Models { public class CalorieCount { // Stores user input for calculating calorie count [Required] [Display(Name = "Calories Consumed")] public int CalorieIntake { get; set; } // Stores the running total [Display(Name = "Total Calories Consumed Today")] public int TotalCalorieCount { get; set; } // This method calculates total calorie count public void CalculateTotalCalorieCount() { // Add CalorieIntake to TotalCalorieCount TotalCalorieCount += CalorieIntake; } } } -
CalorieCounter.cshtml - 向用户显示所有这些并接受输入的网页
@{
ViewBag.Title = "CalorieCounter";
}
<h2>Calorie Counter</h2>
<br />
<hr />
@using (Html.BeginForm())
{
<div class="table-responsive">
<table class="table table-lg">
<tr>
<!-- Displays label and input box for CalorieIntake -->
<td>@Html.LabelFor(m => m.CalorieIntake)</td>
<td>@Html.EditorFor(m => m.CalorieIntake)</td>
</tr>
<tr>
<!-- Displays label and display for TotalCalorieCount -->
<td>@Html.LabelFor(m => m.TotalCalorieCount)</td>
<td>@Html.DisplayFor(m => m.TotalCalorieCount)</td>
</tr>
<tr>
<td></td>
<td>
<!-- Submit button triggers calculation -->
<input type="submit" value="Calculate New Total Calories" class="btn btn-lg btn-success" />
</td>
</tr>
</table>
</div>
}
- HomeController.cs - 处理加载页面并调用模型来处理计算
// Loads Calorie Count Page
// Sets up empty form
[HttpGet]
public ActionResult CalorieCounter()
{
return View();
}
// This action is called when the user clicks the submit button
// The completed form is sent to the back end
[HttpPost]
public ActionResult CalorieCounter(CalorieCount model)
{
if (ModelState.IsValid)
{
model.CalculateTotalCalorieCount();
}
return View(model); // Return the model to the view with all values calculated
}
如果有人能发现此问题并提出修复建议,将非常感谢。
【问题讨论】:
标签: c# html asp.net-mvc