- How to get integer input in ASP.Net Core?
- How to add them in controller and return to View?
This is another part of Controller's Example. In this chapter you will learn how to receive integer input from the user and returns sum of the numbers. However, it is very simple task but the motive is to make you more comfortable with controllers. Each practice you will complete will make you more experienced. So, let’s start the chapter.
Your First ASP.NET CORE MVC Project
@{ ViewBag.Title = "Sum Page"; } <h1>Welcome to Sum Page</h1> <form asp-controller="Home" asp-action="add" method="post"> <span>Enter 1st Number : </span> <input id="Text1" type="text" name="txtFirst" /> <br /><br /> <span>Enter 2nd Number : </span> <input id="Text1" type="text" name="txtSecond" /> <br /><br /> <input id="Submit1" type="submit" value="Add" /> </form> <h2>@ViewBag.SumResult</h2>
Explanation
Here, I created a simple form that contains two text boxes and an Add Button. I have kept textboxes names txtFirst
and txtSecond
. In the controller page I will access these textboxes using this name.
<form asp-controller="Home" asp-action="add" method="post">
This form indicates that all the submission will go to HomeController
and add
action method will be executed.
using System; using Microsoft.AspNetCore.Mvc; namespace SumNumber.Controllers { public class HomeController : Controller { public IActionResult Index() { return View(); } public IActionResult About() { ViewData["Message"] = "Your application description page."; return View(); } public IActionResult Contact() { ViewData["Message"] = "Your contact page."; return View(); } public IActionResult Error() { return View(); } public IActionResult sum() { return View(); } [HttpPost] public IActionResult add() { int num1 = Convert.ToInt32(HttpContext.Request.Form["txtFirst"].ToString()); int num2 = Convert.ToInt32(HttpContext.Request.Form["txtSecond"].ToString()); int result = num1 + num2; ViewBag.SumResult = result.ToString(); return View("sum"); } } }
Explanation
In this program I have added two IAction Methods sum()
and add()
. Sum()
method simply return the sum view page and add()
method receives input from browser, process it, keep results in ViewBag.SumResult and return to browser.
Now, it's time to run your program. Simply press Ctrl + F5 to run your program. It will launch ASP.NET Core website into browser. Simply add /Home/sum at the end of link and press enter.
Summary
In this chapter, you learned how to get integer input and process it in ASP.NET Core Website. In the next chapter, you will learn How to implement multiple submit button in a single Form in ASP.NET Core Website.