Pass Data from Page Model to Razor Page in ASP.NET Core Razor Pages

On the Visual Studio, create new ASP.NET Core Web Application project

Select Empty Template

Click Ok button to Finish




Open Startup.cs file and add new configurations as below:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;

namespace LearnASPNETCoreRazorPagesWithRealApps
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseMvc();
        }
    }
}




Create new folder named Pages. In this folder, create new Razor Page named Index as below:

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

namespace LearnASPNETCoreRazorPagesWithRealApps.Pages
{
    public class IndexModel : PageModel
    {
        public int Age { get; set; }
        public string Username { get; set; }
        public double Price { get; set; }
        public bool Status { get; set; }
        public DateTime Birthday { get; set; }

        public void OnGet()
        {
            Age = 20;
            Username = "abc";
            Price = 4.5;
            Status = true;
            Birthday = DateTime.Now;
        }
    }
}
@page
@model LearnASPNETCoreRazorPagesWithRealApps.Pages.IndexModel
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>

    Age: @Model.Age
    <br />
    Username: @Model.Username
    <br />
    Status: @Model.Status
    <br />
    Price: @Model.Price
    <br />
    Birthday: @Model.Birthday.ToString("MM/dd/yyyy")

</body>
</html>




Open Index Razor Page with following url: http://localhost:1115

Output