【发布时间】:2019-03-06 08:02:37
【问题描述】:
我正在尝试使用 ASP.NET MVC 将两个文本框的总和设置到另一个文本框,我知道这看起来很容易,但我不熟悉 MVC。我只是通过使用@ViewBag.mensaje 来完成此操作。这是我的代码:
模型:
public class suma
{
public int n1 { get; set; }
public int n2 { get; set; }
public int total { get; set; }
}
控制器:
// GET: suma
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(Models.suma model)
{
int x = model.n1;
int y = model.n2;
int total = model.total;
total = x + y;
ViewBag.mensaje = (total).ToString();
return View();
}
查看:
@model bonito2.Models.suma
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
@using (Html.BeginForm("Index", "suma", FormMethod.Post))
{
@Html.TextBoxFor(model => model.n1)<br />
@Html.TextBoxFor(model => model.n2)<br />
<input type="submit" value="Submit" /> <br />
@ViewBag.mensaje
}
我的代码工作OK,但我正在尝试这个工作或在文本框上设置值而不是@ViewBag.mensaje。谢谢。
【问题讨论】:
-
例如将
Total属性添加到您的模型中,并在get方法上写入return n1 + n2(或在ActionMethod 中计算)。
标签: c# asp.net asp.net-mvc model-view-controller