I'm trying to set the sum of two Textboxes to another Textbox using ASP.NET MVC, I know this looks easy but I'm not familiarized with MVC. I just have done this just by using a @ViewBag.mensaje. This is my code:
Model:
public class suma
{
public int n1 { get; set; }
public int n2 { get; set; }
public int total { get; set; }
}
Controller:
// 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();
}
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
}
My code works OK but I'm trying this to work or set the value on a Textbox not in a @ViewBag.mensaje. Thanks.
Totalproperty to your model, and ongetmethod writereturn n1 + n2(or calculate inside ActionMethod).