Form Handling in ASP.NET Core MVC 5

On the Visual Studio, select Create a new project from Get Started

Select ASP.NET Core Web Application




Input Project Name and select Location for new project

Select ASP.NET Core 5.0 Version and select ASP.NET Core Empty Template. Click Create 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;
using Microsoft.Extensions.Hosting;

namespace LearnASPNETCoreMVC5
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();
        }

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

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Demo}/{action=Index}/{id?}");
            });
        }
    }
}

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

Create new class named Account.cs as below:

using System.Collections.Generic;

namespace LearnASPNETCoreMVC5.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 Role { get; set; }
    }
}




Create new class named Language.cs as below:

namespace LearnASPNETCoreMVC5.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 LearnASPNETCoreMVC5.Models
{
    public class Role
    {
        public string Id { get; set; }

        public string Name { get; set; }
    }
}

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

using LearnASPNETCoreMVC5.Models;
using Microsoft.AspNetCore.Mvc.Rendering;
using System.Collections.Generic;

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

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

        public SelectList Roles { get; set; }

    }
}

Create new folder named Controllers. In this folder, create new controller named AccountController.cs as below:

using LearnASPNETCoreMVC5.Models;
using LearnASPNETCoreMVC5.ViewModels;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;

namespace LearnASPNETCoreMVC5.Controllers
{
    [Route("account")]
    public class AccountController : Controller
    {
        [Route("")]
        [Route("index")]
        [Route("~/")]
        public IActionResult Index()
        {
            var accountViewModel = new AccountViewModel();
            accountViewModel.Account = new Account()
            {
                Id = 123,
                Status = true,
                Gender = "male"
            };
            accountViewModel.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  }
            };
            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" }
            };
            accountViewModel.Roles = new Microsoft.AspNetCore.Mvc.Rendering.SelectList(roles, "Id", "Name");
            return View("Index", accountViewModel);
        }

        [Route("save")]
        [HttpPost]
        public IActionResult Save(AccountViewModel accountViewModel, List<Language> Languages)
        {
            accountViewModel.Account.Languages = new List<string>();
            foreach (var language in Languages)
            {
                if (language.IsChecked)
                {
                    accountViewModel.Account.Languages.Add(language.Id);
                }
            }
            ViewBag.Account = accountViewModel.Account;
            return View("Success");
        }

    }
}




Create new folder named Views. In this folder, create new folder named Account and add new views as below:

In Account folder, create new view named Index.cshtml as below:

@model LearnASPNETCoreMVC5.ViewModels.AccountViewModel

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

    <h3>Register Page</h3>
    <form asp-controller="account" asp-action="save" method="post">
        <table border="0" cellpadding="2" cellspacing="2">
            <tr>
                <td>Username</td>
                <td>
                    <input asp-for="Account.Username" />
                </td>
            </tr>
            <tr>
                <td>Password</td>
                <td>
                    <input type="password" asp-for="Account.Password" />
                </td>
            </tr>
            <tr>
                <td valign="top">Description</td>
                <td>
                    <textarea cols="20" rows="5" asp-for="Account.Description"></textarea>
                </td>
            </tr>
            <tr>
                <td>Status</td>
                <td>
                    <input type="checkbox" asp-for="Account.Status" />
                </td>
            </tr>
            <tr>
                <td valign="top">Gender</td>
                <td>
                    <input type="radio" value="male" asp-for="Account.Gender" /> Male
                    <br />
                    <input type="radio" value="female" asp-for="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="Account.Role" asp-items="@Model.Roles"></select>
                </td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td>
                    <input type="submit" value="Save" />
                    <input type="hidden" asp-for="Account.Id" />
                </td>
            </tr>
        </table>
    </form>

</body>
</html>




In Account folder, create new view named Success.cshtml as below:

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

    <h3>Account Info</h3>
    <table border="1" cellpadding="2" cellspacing="2">
        <tr>
            <td>Id</td>
            <td>
                @ViewBag.Account.Id
            </td>
        </tr>
        <tr>
            <td>Username</td>
            <td>
                @ViewBag.Account.Username
            </td>
        </tr>
        <tr>
            <td>Password</td>
            <td>
                @ViewBag.Account.Password
            </td>
        </tr>
        <tr>
            <td>Full Name</td>
            <td>
                @ViewBag.Account.Description
            </td>
        </tr>
        <tr>
            <td>Status</td>
            <td>
                @ViewBag.Account.Status
            </td>
        </tr>
        <tr>
            <td>Gender</td>
            <td>
                @ViewBag.Account.Gender
            </td>
        </tr>
        <tr>
            <td>Role</td>
            <td>
                @ViewBag.Account.Role
            </td>
        </tr>
        <tr>
            <td valign="top">Languages</td>
            <td>
                @foreach (var language in ViewBag.Account.Languages)
                {
                    <span>@language</span>
                    <br />
                }
            </td>
        </tr>
    </table>

</body>
</html>

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




Access Index action in Account controller with following url: http://localhost:48982

Output

Click Save button submit form to Save action in Account controller with following url: http://localhost:48982/account/save

Output