Add two numbers

Add two Numbers

The following code snippets show how we can accept two numbers from the user and display the sum of those numbers in razor pages:

Code behind

using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc;

public class IndexModel : PageModel
{
    public int Result { get; set; }
    public void OnGet(){ }

    public void OnPost(int FirstNum, int SecondNum)
    {
        Result = FirstNum + SecondNum;        
    }
}

Mark up

@page
@model IndexModel

<form method="post">
    @Html.AntiForgeryToken()
    
    <input name="FirstNum">   
    <input name="SecondNum">

    <button type="submit">Add</button>
</form>

@if(@Model.Result!=0){
    <p>Result is @Model.Result</p>
}

The HTML name attribute of the input elements must match with properties of the IndexModel class for automatic binding to happen!

Last updated