ASP Module 2
Getting Started with MVC
Getting Started with MVC
  • Overview
    • Introduction to MVC
  • Understanding MVC
    • Creating an MVC app
    • Add a controller
      • Understand HTTP endpoint
      • Understand basic routing
    • Add a view
      • Understanding shared layouts
      • Setting view title
      • Passing data to view
  • Exercise
    • Add two numbers
      • Using Model
  • Display Movies
    • Add a model
      • Scaffold the index view
      • Scaffold the movies controller
      • Add temp movie data
      • Pass data to index view
    • Implement actions
      • The first create action
      • The second create action
      • The details action method
      • Edit & Delete actions
      • Asynchronous actions
    • Repo link
Powered by GitBook
On this page
  • Using Model
  • Controller code
  • Model Code
  • View Code
  1. Exercise
  2. Add two numbers

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

public class AddNumbersModel
{
    [Required(ErrorMessage = "Please enter a value for Number 1")]
    public int Number1 { get; set; }

    [Required(ErrorMessage = "Please enter a value for Number 2")]
    public int Number2 { get; set; }
}

View Code

@model AddNumbersModel
@{
    ViewData["Title"] = "Add Numbers";
}

<h1>Add Numbers</h1>

<form asp-action="Index" method="post">
    <div>
        <label asp-for="Number1">Number 1:</label>
        <input asp-for="Number1" required>
        <span asp-validation-for="Number1" class="text-danger"></span>
    </div>
    <div>
        <label asp-for="Number2">Number 2:</label>
        <input asp-for="Number2" required>
        <span asp-validation-for="Number2" class="text-danger"></span>
    </div>
    <button type="submit">Add</button>
</form>

@if (ViewBag.Result != null)
{
    <p>The result of adding the two numbers is @ViewBag.Result.</p>
}

@section Scripts {
    <partial name="_ValidationScriptsPartial" />
}

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.

PreviousAdd two numbersNextAdd a model

Last updated 2 years ago