Add two numbers
Add two numbers
Let us add 2 numbers using mvc architecture. We could do this in a separate controller or in the existing home controller like shown below
Controller Code
public class HomeController : Controller
{
[HttpGet]
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult Index(int firstNum, int secondNum)
{
int result = firstNum + secondNum;
ViewBag.FirstNum = firstNum;
ViewBag.SecondNum = secondNum;
ViewBag.Result = result;
return View();
}
}
View Code
@model int
<h1>Add Numbers</h1>
<form method="post">
<label for="number1">Number 1:</label>
<input type="number" name="firstNum" required>
<label for="number2">Number 2:</label>
<input type="number" name="secondNum" required>
<button type="submit">Add</button>
</form>
@if (ViewBag.Result != null)
{
<p>The result of adding @ViewBag.FirstNum and @ViewBag.SecondNum is @ViewBag.Result.</p>
}
In ASP.NET Core MVC, there are three ways to pass data from a controller to a view:
using
ViewData
,using
ViewBag
, andusing strongly-typed models.
Last updated