Form Handling 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();
        }
    }
}

Select Views folder and right click to select Add\New Item Menu

Select Web\ASP.NET in left side. Select Razor View Imports item and click Add button to Finish

In _ViewImports.cshtml file and TagHelpers library as below:

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers




Create new folder named Models. In Models folder, create new entities class as below:

Create new class named Hobby.cs as below:

namespace LearnASPNETCoreRazorPagesWithRealApps.Models
{
    public class Hobby
    {
        public string Id { get; set; }

        public string Name { get; set; }
    }
}

Create new class named Language.cs as below:

namespace LearnASPNETCoreRazorPagesWithRealApps.Models
{
    public class Language
    {
        public string Id { get; set; }

        public string Name { get; set; }

        public bool IsChecked { get; set; }
    }
}

Create new class named Role.cs as below:

namespace LearnASPNETCoreRazorPagesWithRealApps.Models
{
    public class Role
    {
        public string Id { get; set; }

        public string Name { get; set; }
    }
}

Create new class named Account.cs as below:

using System.Collections.Generic;

namespace LearnASPNETCoreRazorPagesWithRealApps.Models
{
    public class Account
    {
        public int Id { get; set; }

        public string Username { get; set; }

        public string Password { get; set; }

        public string Description { get; set; }

        public bool Status { get; set; }

        public List<string> Languages { get; set; }

        public string Gender { get; set; }

        public string[] Hobbies { get; set; }

        public string Role { get; set; }
    }
}




Create new folder named ViewModels, create new class named AccountViewModel.cs as below:

using LearnASPNETCoreRazorPagesWithRealApps.Models;
using Microsoft.AspNetCore.Mvc.Rendering;

namespace LearnASPNETCoreRazorPagesWithRealApps.ViewModels
{
    public class AccountViewModel
    {
        public Account account { get; set; }

        public SelectList Roles { get; set; }

        public SelectList Hobbies { get; set; }
    }
}

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

using LearnASPNETCoreRazorPagesWithRealApps.Models;
using LearnASPNETCoreRazorPagesWithRealApps.ViewModels;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using System.Collections.Generic;
using System.Diagnostics;

namespace LearnASPNETCoreRazorPagesWithRealApps.Pages
{
    public class IndexModel : PageModel
    {
        [BindProperty]
        public AccountViewModel accountViewModel { get; set; }

        public List<Language> Languages { get; set; }

        public IndexModel()
        {
            Languages = new List<Language>() {
                new Language() { Id = "l1", Name = "Language 1", IsChecked = true  },
                new Language() { Id = "l2", Name = "Language 2", IsChecked = false  },
                new Language() { Id = "l3", Name = "Language 3", IsChecked = true  },
                new Language() { Id = "l4", Name = "Language 4", IsChecked = false  },
                new Language() { Id = "l5", Name = "Language 5", IsChecked = false  }
            };
        }

        public void OnGet()
        {
            var roles = new List<Role>() {
                new Role { Id = "r1", Name = "Role 1" },
                new Role { Id = "r2", Name = "Role 2" },
                new Role { Id = "r3", Name = "Role 3" },
                new Role { Id = "r4", Name = "Role 4" }
            };

            var hobbies = new List<Hobby>() {
                new Hobby { Id = "hob1", Name = "Hobby 1" },
                new Hobby { Id = "hob2", Name = "Hobby 2" },
                new Hobby { Id = "hob3", Name = "Hobby 3" },
                new Hobby { Id = "hob4", Name = "Hobby 4" },
                new Hobby { Id = "hob5", Name = "Hobby 5" }
            };

            accountViewModel = new AccountViewModel()
            {
                Roles = new SelectList(roles, "Id", "Name"),
                Hobbies = new SelectList(hobbies, "Id", "Name"),
                account = new Account()
                {
                    Status = true,
                    Gender = "male",
                    Hobbies = new string[] { "hob1", "hob3" }
                }
            };
        }

        public IActionResult OnPost()
        {
            var account = accountViewModel.account;
            account.Languages = new List<string>();
            foreach (var language in Languages)
            {
                if (language.IsChecked)
                {
                    account.Languages.Add(language.Id);
                }
            }
            Debug.WriteLine("Account Information");
            Debug.WriteLine("Username: " + account.Username);
            Debug.WriteLine("Password: " + account.Password);
            Debug.WriteLine("Description: " + account.Description);
            Debug.WriteLine("Gender: " + account.Gender);
            Debug.WriteLine("Status: " + account.Status);
            Debug.WriteLine("Role: " + account.Role);
            Debug.WriteLine("Language List");
            foreach (var language in account.Languages)
            {
                Debug.WriteLine("\t" + language);
            }
            Debug.WriteLine("Hobby List");
            foreach (var hobby in account.Hobbies)
            {
                Debug.WriteLine("\t" + hobby);
            }
            return RedirectToPage("Success");
        }

    }
}




@page
@model LearnASPNETCoreRazorPagesWithRealApps.Pages.IndexModel
@{
    Layout = null;
}

<!DOCTYPE html>

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

    <h3>Register Account</h3>
    <form asp-page="index" method="post">
        <table border="0" cellpadding="2" cellspacing="2">
            <tr>
                <td>Username</td>
                <td>
                    <input asp-for="@Model.accountViewModel.account.Username" />
                </td>
            </tr>
            <tr>
                <td>Password</td>
                <td>
                    <input type="password" asp-for="@Model.accountViewModel.account.Password" />
                </td>
            </tr>
            <tr>
                <td valign="top">Description</td>
                <td>
                    <textarea cols="20" rows="5" asp-for="@Model.accountViewModel.account.Description"></textarea>
                </td>
            </tr>
            <tr>
                <td>Status</td>
                <td>
                    <input type="checkbox" asp-for="@Model.accountViewModel.account.Status" />
                </td>
            </tr>
            <tr>
                <td valign="top">Gender</td>
                <td>
                    <input type="radio" value="male" asp-for="@Model.accountViewModel.account.Gender" /> Male
                    <br />
                    <input type="radio" value="female" asp-for="@Model.accountViewModel.account.Gender" /> Female
                </td>
            </tr>
            <tr>
                <td>Languages</td>
                <td>
                    @for (var i = 0; i < Model.Languages.Count; i++)
                    {
                        <input type="hidden" asp-for="@Model.Languages[i].Id" />
                        <input type="hidden" asp-for="@Model.Languages[i].Name" />
                        <input type="checkbox" asp-for="@Model.Languages[i].IsChecked" />
                        <label asp-for="@Model.Languages[i].Id">@Model.Languages[i].Name</label>
                    }
                </td>
            </tr>
            <tr>
                <td>Role</td>
                <td>
                    <select asp-for="@Model.accountViewModel.account.Role" asp-items="@Model.accountViewModel.Roles"></select>
                </td>
            </tr>
            <tr>
                <td>Hobbies</td>
                <td>
                    <select asp-for="@Model.accountViewModel.account.Hobbies" asp-items="@Model.accountViewModel.Hobbies" multiple="multiple"></select>
                </td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td>
                    <input type="submit" value="Save" />
                    <input type="hidden" asp-for="@Model.accountViewModel.account.Id" />
                </td>
            </tr>
        </table>
    </form>

</body>
</html>

In Pages folder, create new Razor Page named Success as below:

@page
@model LearnASPNETCoreRazorPagesWithRealApps.Pages.SuccessModel
@{
    Layout = null;
}

<!DOCTYPE html>

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

    <h3>Success Page</h3>

</body>
</html>
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace LearnASPNETCoreRazorPagesWithRealApps.Pages
{
    public class SuccessModel : PageModel
    {
        public void OnGet()
        {
        }
    }
}




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

Input data to form and click Save button submit form to OnPost action in Index razor page and redirect to Success page with following url: http://localhost:1115/Success

Output in Console

Account Information
Username: acc1
Password: 123
Description: ABC
Gender: male
Status: True
Role: r1
Language List
	l1
	l3
Hobby List
	hob1
	hob3