使用ASP创建计算器.净MVC
本文关键字:MVC 计算器 创建 ASP 使用 | 更新日期: 2023-09-27 17:51:10
我刚开始使用ASP。Net,目前我试图创建一个简单的计算器只是使用MVC。我有我的视图布局,但我有麻烦调用我想要的对象。如果你知道任何好的指南或帮助解决我的问题,那就太好了。对于我的结果行动,我正在看一个指南,它让我不知道该怎么做。观点:
@using CalculatorApp.Models
@{
ViewBag.Title = "Index";
}
@using (Html.BeginForm("Index", "CalcController")) {
<div>
<h2>@Html.Label("Enter first number") : @Html.TextBox("num1")</h2>
<h2>@Html.Label("Enter second number") : @Html.TextBox("num2")</h2>
</div>
<div>
<h2>
@Html.RadioButton("calkey", "0") +
<br>
@Html.RadioButton("calkey", "1") -
<br>
@Html.RadioButton("calkey", "2") *
<br>
@Html.RadioButton("calkey", "3") /
</h2>
</div>
<input type="submit" name="Index" value="Index"/>
}
模型:
namespace CalculatorApp.Models
{
public class Calculations : Controller
{
//
// GET: /Calculations/
public int num1 { get; set; }
public int num2 { get; set; }
public int result { get; set; }
public bool add { get; set; }
public bool sub { get; set; }
public bool mult { get; set; }
public bool div { get; set; }
}
}
控制器:
namespace CalculatorApp.Controllers
{
public class CalcController : Controller
{
public ActionResult Index(Calculations calc)
{
int selectedFunction = Convert.ToInt32(Request["calkey"]);
switch (selectedFunction)
{
case 0:
calc.result = calc.num1 + calc.num2;
break;
case 1:
calc.result = calc.num1 - calc.num2;
break;
case 2:
calc.result = calc.num1 * calc.num2;
break;
case 3:
if (calc.num2 > 0)
{
calc.result = calc.num1 / calc.num2;
}
break;
}
return View(calc);
}
public ActionResult Result(Calculations calc)
{
return View(calc);
}
}
}
我想解决的问题是,当我按下提交按钮时,如何使计算工作。我不知道该从何说起。
我注意到的几个问题
-
At Your View你必须在Html中移除控制器。BeginForm (put controller name (Calc) only)
将
Html.BeginForm("Index", "CalcController")
改为Html.BeginForm("Index", "Calc")
-
在你的模型你不应该继承控制器
将
public class Calculations : Controller
改为public class Calculations
-
在您的控制器
当你在索引方法上发布你的数据时,你可以从控制器中删除结果方法。之后添加新的名为'Index'的get方法,比如
public ActionResult Index() { return View(); }
最后你必须在视图中显示你的结果。所以在索引视图中创建一个元素,比如@Html.TextBox("result")
如果你想在Result Method中发布数据
- 将索引替换为
@Html.BeginForm
- 从索引方法中删除所有代码(参数也)(只放置返回视图())并将这些代码粘贴到结果方法中。