Using Model

Using Model

We could have used a model instead of dealing with primitive types as shown below

Controller code

public class HomeController : Controller
{
    [HttpGet]
    public IActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public IActionResult Index(AddNumbersModel model)
    {
        if (ModelState.IsValid)
        {
            int result = model.Number1 + model.Number2;
            ViewBag.Result = result;
        }
        return View(model);
    }
}

Model Code

View Code

In this example, we have created a strongly-typed AddNumbersModel class that has two properties Number1 and Number2, and decorated them with Required attributes to ensure that they are not null or empty.

Last updated